c++ - 如何告诉 stringstream 忽略空终止符?

标签 c++ istream

有什么方法可以告诉字符串流忽略空终止字符并读取一定数量的字符吗?

正如您从这个最小示例中看到的,即使 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/

相关文章:

c++ - 没有匹配的构造函数来初始化我的自定义分配器

c++ - 读取文件时堆损坏

C++ 不要进入我的cin

c++ - 显示集合的第一个元素

c++ - 替换字符串中的字符需要成本吗?

c++ - 将 istream 中的字符回显到异常 "device"

c++ - boost::lexical_cast 无法识别重载的 istream 运算符

c++ - Streams 中的内联忽略

c++ - Windows 调试 Api - 分离不起作用

c++ - 如何将 QByteArray 转换为 std::istream 或 std::ifstream?