Fstream fail()

Hey guys I'm reading Bjarnes practices and principles and I have a quetion regarding an fstream in this case it is an ifstream well ofstream to be more precise

I have a text file with the following 1 2 3 4 5 6 *,the * is the terminator

anyway when in >> fails and the stream is put into a fail state how come we don't have to use the unget to put the character back into the stream before getting the char ch from the stream?

thanks

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
#include <iostream>
#include <fstream>
#include <vector>

using namespace std;


vector<int> vec;

void input(ifstream &in,char terminator){

   int num = 0;

   while(in >> num){

     cout << num << endl;
     vec.push_back(num);
   }
   if(in.bad()){

      cout << "cant recover" << endl;
      return;
   }
   if(in.fail()){

    in.clear();

    char ch;
    in >> ch;
    cout << ch << endl;

   }
}

how come we don't have to use the unget to put the character back into the stream before getting the char ch from the stream?
If the stream is in "fail" state, it's pretty much unusable. Calling unget() won't have any effect.
thanks kbw

but when the goes into a fail state after reading something wrong such as a char or string for an int the fail bit is true in turn putting the stream into a fail state AND it leaves the char or string it tried to put into the int in the buffer?

thanks
Yes when you try to enter a character into an int, the stream will fail setting the proper "fail" flag and leaving the offending character (and anything else) in the input buffer. When a stream is in a fail condition no operations on the stream can occur until the stream state is reset.

I hope this answers your question.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
#include <sstream>
#include <iostream>
#include <string>

int main()
{
	std::stringstream ss("1 2 hello world");

	// read int's until we fail
	int val = -1;
	while (ss >> val)
		std::cout << val << std::endl;

	if (ss.fail())
		ss.clear();

	// read remainder
	std::string str; 
	std::getline(ss, str);
	std::cout << "str=\"" << str << '\"' << std::endl;
}

1
2
str="hello world"
Last edited on
thanks guys :)
Topic archived. No new replies allowed.