C++ 能否输入换行符(C+;+;)?

C++ 能否输入换行符(C+;+;)?,c++,newline,C++,Newline,假设我希望能够使用格式(即换行符、制表符)输出某些内容 您必须自己处理输入字符串。一个简单的实现如下所示: 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

假设我希望能够使用格式(即换行符、制表符)输出某些内容


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

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;
}
std::string UnescapeString(std::string输入){
大小\u t位置=输入。查找(\\);
while(位置!=std::string::npos){
//确保斜杠后面还有另一个字符
如果(位置+1

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

在哪个操作系统上<代码>\n
通常是行尾标记!似乎您想要取消转义字符串的转义。您需要手动执行此操作。字符串操作不是魔术。在字符串文字中,转义字符有特殊语法,但用户输入的输入不是字符串文字。它不是语言的一部分,因此它不是自动取消替换的(那将是可怕的)。因此,您需要自己在字符串中找到
\n
,并用换行符替换它。请注意,您正在搜索两个字符:'\\'和'n'。这两个应该用一个“\n”重新计算,我可以问一下,为什么我必须搜索“//”而不仅仅是“/”?您必须搜索“\\”,因为代码中的正斜杠表示转义序列的开始。这是为了消除用户意图的歧义。如果有人写了“\”,编译器如何确定作者是指字符串中的一个正斜杠,而不是以双引号开头的字符串?“\\”只是转义序列,意思是“发出一个正斜杠”。它本质上与“\n”相同,但它是一个斜杠而不是换行符。
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;
}