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
.
In addition to the other answer explaining the underlying problem (creating a std::string
from a char*
), here's one (of many) ways around the problem, using std::string_literals
:
#include <iostream>
#include <string>
#include <sstream>
int main(){
using namespace std::string_literals;
const std::string str_with_null = "1\0002"s;
std::stringstream ss(str_with_null);
char c;
while (ss.get(c)) {
std::cout << static_cast<int>(c) << '\n';
}
}
When run, this should print out:
49
0
50
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.