Reputation: 383
My understanding of iostream has always been that when an input conversion fails, the data remains in the stream to be read after clearing the error. But I have an example that does not always work that way, and I would like to know if the behavior is correct. If so, could someone point me at some good documentation of the actual rules?
This small program represents the idea of using an i/o failure to read an optional repeat count and a string.
#include <iostream>
#include <string>
int main()
{
int cnt;
std::cout << "in: ";
std::cin >> cnt;
if(!std::cin) {
cnt = 1;
std::cin.clear();
}
std::string s;
std::cin >> s;
std::cout << "out: " << cnt << " [" << s << "]" << std::endl;
}
So, here's how it runs:
[me@localhost tmp]$ ./bother
in: 16 boxes
out: 16 [boxes]
[me@localhost tmp]$ ./bother
in: hatrack
out: 1 [hatrack]
[me@localhost tmp]$ ./bother
in: some things
out: 1 [some]
[me@localhost tmp]$ ./bother
in: 23miles
out: 23 [miles]
[me@localhost tmp]$ ./bother
in: @(#&$(@#&$ computer
out: 1 [@(#&$(@#&$]
So it mostly works. When there's a number first, it is read, then the string is. When I give a non-numeric first, the read fails, the count is set to 1 and the non-numeric input is read. But this breaks:
[me@localhost tmp]$ ./bother
in: + smith
out: 1 [smith]
The + fails the integer read because it's not enough to make a number, but the + does not remain on the stream to be picked up by the string read. Likewise with -. If it reads the + or - as a zero, that would be reasonable, but then the read should succeed and cnt should show that zero.
Perhaps this is correct behavior, and I've just always been wrong about what it is supposed to do. If so, what are the rules?
Your advice appreciated.
Upvotes: 4
Views: 69
Reputation: 36389
Plus and minus are valid parts of an integer and so are read, when the next character is read the stream fails and that character is left in the stream but the leading sign character is not put back into the stream.
See https://en.cppreference.com/w/cpp/locale/num_get/get for the full rules
Upvotes: 2