std::stringstream can be used as bytestream?

It's very cold.

Anyway, I'm making a program to scan bytecode.
I want to make it can scan both std::istream and std::vector<char>.

So, when it gets vector, it converts the vector to stringstream.
But there is a problem.
After the conversion, the size of stringstream increases one byte
(adding EOF(-1) to the tail).

Ignoring the last byte isn't so difficult,
but I want to know why this happens.
Would you give me some advises.

Here is a sample.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#include <vector>
#include <sstream>
#include <string>

using namespace std;

int main()
{
	// not unsigned for std::string.
	const char binary[]={
		1,2,3,4,5,6,7,8,
		9,0,1,2,3,4,5,6
	};
	
	string str(binary);
	
	vector<char> v;
	stringstream ss;
	
	for (unsigned i=0; i<sizeof(binary)/sizeof(char); ++i) {
		v.push_back(binary[i]);
		ss << binary[i];
	}

		
	cout << sizeof(binary)/sizeof(char) << endl; // 16
	cout << str.size() << endl;                  // 9, but it's ok.
	cout << v.size() << endl;                    // 16
	
	cout << ss.str().size() << endl;             // 16 <- sure?
	
	vector<char> v2;
	while (!ss.eof()) {
		v2.push_back(ss.get());
	}
	cout << v2.size() << endl;	             // 17 <- why?
	cout << (int)v2[v2.size()-1] << endl;        // -1 <- why eof pushed?
	return 0;
}


Thank you.
Last edited on
first of all, replace
string str(binary);
by
string str(binary, sizeof binary);
And then, replace
1
2
3
while (!ss.eof()) {
    v2.push_back(ss.get());
}
by

1
2
3
for(char ch; ss.get(ch); ) {
    v2.push_back(ch);
}

the "while not eof" construct is (almost) always an error
Last edited on
Thank you, Cubbi.

I'll correct them,
although I've written many loops using eof()...
I've written many loops using eof()...

Why?

To answer the original "why eof pushed?", in this program, you've iterated through the 16-byte stream "ss" 17 times. On the 17th iteration, ss.get() was unable to read from the stream, so it executed ss.setstate(eofbit) and returned EOF, which you've push_back()'ed into the vector.
After the 17th iteration, ss.eof() returned true (since eofbit was now set), and the loop ended.

I've written many loops using eof()...

Why?


I've already written some programs which may cause this problem before.
So I must fix may loops.

I didn't notice iostream's last EOF,
because I usually output these values in character and didn't count them.

I've checked that other istreams returns EOF, too.

Thank you.
Can we make this EOF behavoir as sticky? File IO is an often done operation and quite a lot of developers are still testing against the EOF to detect end of file or input. A lot of times it is (almost) always an error.

Thanks.
Topic archived. No new replies allowed.