有什么方法可以告诉字符串流忽略空终止字符并读取一定数量的字符吗?
正如您从这个最小示例中看到的,即使 char 数组由 3 个字符组成,字符串流也会在第二个位置终止:
#include <sstream>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
char test[3];
test[0] = '1';
test[1] = '\0';
test[2] = '2';
stringstream ss(test);
char c;
cout << "start" << endl;
while (ss.get(c)) {
cout << c << endl;
}
if (ss.eof()) {
cout << "eof" << endl;
}
}
$ ./a.out
start
1
eof
最佳答案
这个问题不是关于字符串流的。问题是您正在从 const char*
为该 stringstream 构造函数参数隐式构造 std::string
,并使用需要 C 字符串的重载来实现。因此,很自然地,您应该期待类似 C 字符串的行为。
相反,您可以使用 std::string(const char*, std::size_t)
构造函数形成参数,或者使用 .write 将数据发送到默认构造的字符串流
。
关于c++ - 如何告诉 stringstream 忽略空终止符?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58675324/