Accelerated C++ istream question

I'm in chapter 5 and there is a thing I don't understand. When creating for example a function to insert input words to a vector why does the book put if (in)

I tried the code without it and the function still works the same way... Could you show me an example to see what it does?

I don't understand either what in.clear() does. Another example or explanation please?

1
2
3
4
5
6
7
8
9
10
  istream& readToVector(istream& in, vector<string>& vec) {
	if (in) {
		vec.clear();
		string word;
		while (in >> word)
			vec.push_back(word);
		in.clear();
	}
	return in;
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  istream& readToVector(istream& in, vector<string>& vec) {

	if (in) { // if the stream in is not in a failed state 
                  // ie. clear the vector and try to read into it only if we can read from the stream

		vec.clear();
		string word;
		while (in >> word) // when this loop ends, the stream would be in a failed state
			vec.push_back(word);
                
                // the stream is now in a failed state; clear the failed state of the stream 
                // before returning to the caller. This would facilitate constructs like
                // if( readToVector( my_stream, my_vec ) { /* read was successful, do something */ } 
		in.clear();
	}
	return in;
}
You want me to clear the vector before calling the function? It does the same, sorry I don't understand that part (I understood in.clear() ).
If, on entry, the stream is already in a failed state, the function would not modify the vector; it remains unchanged. If the stream is in a readable state, it first clears the vector and then reads into it.
Oh, I see. Thanks!
Topic archived. No new replies allowed.