using 'std::cin>>int>>string' works without whitespace?

Viewed 97

I've started learning C++ recently, and I was experimenting with cout and cin with the code below:

#include <iostream>
using namespace std;

int main()
{
    int x = 0;
    string y;

    cin >> x >> y;
    cout << "x: " << x << '\n';
    cout << "y: " << y << '\n';
}

I was taught that the input would have to be seperated with whitespaces for something like this to work. But, when I input into the console something like 420foo, cin works perfectly to seperate and assign 420 as x and foo as y, giving the output:

x: 420
y: foo

This seems pretty convenient, but I'm not sure how this works, or if this is unintended... I've tried looking through some sources online, but to no avail. Any help would be appreciated for uncovering this mystery!

3 Answers

The input operators >> are greedy. They will read as many characters as they can that match the destination type.

For the input 420foo the input to x can read the three digits, but when it finds the f it will stop reading, leaving the f in the input buffer to be read next.

This works because of the types of the data you are reading in

int x = 0;
string y;
cin >> x >> y;

This will first try to read an int into x. It reads 4, 2, 0 and then it sees an f. So it simply puts 420 into x, and then continues reading. It finds foo, which is a string and you get the result you see.

The fact that this works is probably accidental. If you swap the order of reads, like this

int x = 0;
string y;
cin >> y >> x;

and provide the same input, it will read 420foo into y (because 420foo is a perfectly fine string), and then wait for the input for x.

In particular, if you provide the input foo420, you might expect that the string y will contain foo, and the int x will contain 420, but that's not what happens. y will be foo420, and it won't read anything into x.

Space separated input is usually the way to provide data like this to a program.

This is actually intentionally. For numeric types, all characters up to the first "non-numeric" character are extracted by operator>> and parsed as a number.

A whitespace is just one special case of a non-numeric character. By the way, operator>> always starts by removing all leading whitespace. This is why it is best to use whitespaces for separating inputs. Please note that some numeric types may contain non-digit characters, e. g. dot, comma, e, + or -. You can end up with unexpected results or errors when you're not using whitespaces.

Related