- 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
}
- 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.