是否有任何方法可以告诉字符串流忽略以null结尾的char并仍然读取一定数量的char?
从这个最小的示例中可以看到,即使char数组由3个char组成,stringstream也会在第二个位置终止:
#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
您不能-这是所有C样式字符串都可以使用的假设。处理C字符串的大多数类和函数都假定它们以null结尾。
要使用\0
作为有效字符,请使用std::string
。此类将size存储为单独的成员,这意味着无需使用特殊值来显示结尾在哪里:
#include <sstream>
#include <iostream>
using namespace std;
int main(int argc, char* argv[]) {
std::string test(3, '\0');
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;
}
}
请注意,由于上述原因,std::string test = "1\02";
不会起作用。