gpt4 book ai didi

c++ - Stringstream 不复制新行

转载 作者:塔克拉玛干 更新时间:2023-11-03 07:26:36 25 4
gpt4 key购买 nike

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

#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();

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

最佳答案

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

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

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

overloads operator<< to behave as described in ostream::operator<< for c-strings

所提及的行为已得到解释 here :

(2) character sequence Inserts the C-string s into os. The terminating null character is not inserted into os. The length of the c-string is determined beforehand (as if calling strlen).

斯特伦 documentation表示结果只受

the terminating null-character

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

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

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

将向您展示这确实会发生。

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

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

您应该尝试一下。

关于c++ - Stringstream 不复制新行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18462809/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com