0

What will happen if the input stream is invalid? For example, as follows:

int main()
{
    int value;
    while(!(cin>>value).eof());
}

If the entered sequence is : 1 2 3 q 4 5, the while will fall into endless loop when the cin scans 'q' and the value continues to be 3. My questions are: 1. Why can't cin ignore 'q' and proceed to scan 4? 2. What's the underlying implementation fo input stream? Are there any materials I can refer to ?

Thank you!

sophistcxf
  • 111
  • 3

1 Answers1

3
  1. Why can't cin ignore 'q' and proceed to scan 4?

You can if you want to. You could get that effect with the following:

int value;
while(std::cin>>value);
if (!std::cin)
{
    std::cin.clear(); // clear error state
    std::cin.ignore(); // ignore the q
    while(std::cin>>value); // read rest of values until 5
}

std::cin >> value just does not do that by default, as the behavior desired is different depending on the program. For many people it would be undesirable for std::cin to ignore a read failure and keep scanning. The default behavior allows you the programmer to decide what to do on failure.

Also, note that eof() is for checking for end of file. You should not use it to check if a read was successful or not. The common idiom would be:

while(std::cin>>value)
{
    // Do stuff
}
  1. What's the underlying implementation fo input stream? Are there any materials I can refer to ?

std::cin is a global static object and is defined like so:

extern std::istream cin;

In other words it is an instance of std::basic_istream<char> (std::istream is a typedef for it).

If you would like more information, here are some references:

http://en.cppreference.com/w/cpp/io/cin

https://github.com/cplusplus/draft

However, most likely you would benefit from a good C++ book.

If you want to get into deep iostreams, I also recommend these articles.

Community
  • 1
  • 1
Jesse Good
  • 50,901
  • 14
  • 124
  • 166