3

当我将字符串传递到字符串流时,特殊字符会消失。我试过这个可以直接测试的代码:

#include <iostream>
#include <sstream>
using namespace std;

int main(int argc, char* argv[]) {

 string txt("hehehaha\n\t hehe\n\n<New>\n\ttest:\t130\n\ttest_end:\n<New_end>\n");

 cout << txt << endl; // No problem with new lines and tabs

 stringstream stream;
 stream << txt;
 string s;
 while(stream >> s) {
  cout << s;  // Here special characters like '\n' and '\t' don't exist anymore.
 }
 cout << "\n\n";

 return 0;
}

我能做些什么来克服这个问题?

编辑:我试过这个:

stream << txt.c_str();

它奏效了。但我不知道为什么...

4

2 回答 2

2

基本上,你只是打印错了,应该是:

cout << stream.str() << endl;

一些细节。您正在调用operator<<(string)哪个

重载 operator<< 以按照 ostream::operator<< for c-strings 中的描述进行操作

这里解释了所指的行为:

(2) 字符序列 将 C 字符串 s 插入到 os 中。终止空字符未插入到 os 中。c 字符串的长度是预先确定的(就像调用 strlen 一样)。

Strlen文档说结果只受

终止的空字符

实际上,strlen(tmp)在您的示例中输出 55​​。

因此,流被“分配”到输入字符串中第 55 个字符的所有内容。

cout << stream.str() << endl;

会告诉你这确实是发生了什么。

stream << txt括号:您可以通过设置/取消设置标志来修改行的行为,如

 stream.unsetf ( std::ios::skipws );

您应该尝试一下。

于 2013-08-27T10:40:58.173 回答
0

该声明

while(stream >> s)

是问题所在,它在每次调用时给你一个令牌,使用空格进行拆分,因此忽略它们。

于 2013-08-27T10:38:47.947 回答