你能算出一个输入的换行符(C++)吗?

Can you cout an entered newline character (C++)?

假设我希望能够通过格式化(即换行符、制表符)计算出一些内容

#include <iostream>
using namespace std;
string str;
int main() 
{
getline(cin, str);
cout << str;
}

所以我会输入类似 Hey\nThere 的内容以在 hey 和 there 之间换行。但是,它准确地输出了我输入的内容 (Hey\nThere)。是否可以像我希望的那样计算它(见下文)?

Hey
There

您必须自己处理输入字符串。一个简单的实现如下:

std::string UnescapeString( std::string input ){
    size_t position = input.find("\");
    while( position != std::string::npos ){
        //Make sure there's another character after the slash
        if( position + 1 < input.size() ){
            switch(input[position + 1]){
                case 'n': input.replace( position, 2, "\n"); break;
                case 't': input.replace( position, 2, "\t"); break;
                case 'r': input.replace( position, 2, "\r"); break;
                default: break;
            }
        }
        position = input.find("\", position + 1);
    }
    return input;
}

您当然可以为 char 转义序列、Unicode 转义序列和其他可能需要的转义序列添加更复杂的解析规则。