Is there any way to tell a stringstream to ignore a null terminating char and read a certain amount of chars anyway?
As you can see from this minimum example, even though the char array consists of 3 chars, the stringstream terminates at the second position:
#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
This question is not about stringstreams. The problem is you are implicitly constructing a std::string
from a const char*
for that stringstream constructor argument, and doing so using the overload that expects a C-string. So, naturally, you should expect C-string-like behaviour.
Instead you can form the argument using the std::string(const char*, std::size_t)
constructor, or send the data to a default-constructed stringstream using .write
.