How cin interprets a .

I have a student who made a mistake in creating an input file. His line should have been:
P-123 12 3.88
ie partNumber (a string) quantity (an int) and cost (a double)
His line was:
P-132 3.88
The line to read the file was:
while(fin >> partNumber >> quantity >> cost)

It "worked" in that it read P-132 into partNumber, 3 into quantity and .88 into cost. It apparently interpreted the . as whitespace. cin leaves whitespace in the stream, so the .88 would be a valid double value. I just don't understand why the . would be interpreted as whitespace! Just looking for an explanation. I'd have expected a runtime error!
When parsing integer, parsing stops as soon as any non-digit is found, not only whitespace.
It is completely valid to enter something like "12Hello" instead of "12 Hello" when asked for integer and a word.

Also it would never be a runtime error, even if you enter a letters instead of number. It would just send stream into failed state (unless you mess with stream exception mask).
Last edited on
> I just don't understand why the . would be interpreted as whitespace!

It is not interpreted as whitespace. It is interpreted as a character that can't be be used to form a valid base-10 integer (and character extraction to form the integer stops when the dot is encountered.)

The formatted input operation eventually calls std::strtoll() (in this case, with base==10) to perform the conversion from sequence-of-characters to signed-integer-value.
http://en.cppreference.com/w/cpp/string/byte/strtol

1
2
3
4
5
6
7
int a ;
char b ;
int c ;
std::cin >> a >> b >> c ; // type in 123g45
std::cout << a << '\n' // 123
          << b << '\n' // g
          << c << '\n' ; // 45 
. I just don't understand why the . would be interpreted as whitespace!

It's not interpreted as whitespace, it's interpreted as an illegal character. The extraction operator knows that an integer can't contain anything other than one of the digits or the sign characters, anything else is put back into the stream to be ready for the next stream operation.

I'd have expected a runtime error!

The only runtime error you would get would be bad data, which did happen. Remember the extraction operator>> normally handles exceptions internally. If you want to have an exception thrown you'll need to use the ios.exceptions mechanism. http://www.cplusplus.com/reference/ios/ios/exceptions/
Topic archived. No new replies allowed.