CeNiEi
CeNiEi

Reputation: 107

why is std::cin not reading from the start

I was looking at a question involving how the std::cin works. This was the question:

What does the following program do if, when it asks you for input, you type two names(for example Samuel Beckett)?

#include <iostream>
#include <string>

int main() {

    std::cout << "What is your name? ";
    std::string name;
    std::cin >> name;
    std::cout << "Hello, " << name << std::endl << "And what is yours? ";

    std::cin >> name;
    std::cout << "Hello, " << name << std::endl << "; nice to meet you too!" << std::endl;

    return 0;
}

I expected the output to be :

What is your name? Samuel Beckett
Hello, Samuel
And what is yours? Hello, Samuel
; nice to meet you too!

But the output is:

What is your name? Samuel Beckett
Hello, Samuel
And what is yours? Hello, Beckett
; nice to meet you too!

Can anybody please help, how std::cin is working ?

I know that if i do this:

    std::string a, b;
    std::cin >> a >> b;

and type two words in, then a will have the first word and b will have the second.But why is this happening? Isn't std::cin supposed to initially discard all whitespace first and then read characters till another whitespace is reached???

Any help is deeply appreciated.

Upvotes: 1

Views: 288

Answers (2)

Remy Lebeau
Remy Lebeau

Reputation: 597600

What does the following program do if, when it asks you for input, you type two names (for example Samuel Beckett)?

operator>> stops reading when it encounters whitespace (amongst other conditions). So, the first call to >> returns only Samuel, leaving Beckett in the input buffer for the next call to >> to return. Which is exactly what you see happen.

I know that if i do this:

std::string a, b;
std::cin >> a >> b;

and type two words in, then a will have the first word and b will have the second.

There is no difference whatsoever between

std::cin >> a >> b;

And

std::cin >> a;
std::cin >> b;

In the first case, operator>> returns an std::istream& reference to the stream being read from, which is what allows multiple operations to be chained together. But the same operations can also be done in separate statements, too.

Isn't std::cin supposed to initially discard all whitespace first and then read characters till another whitespace is reached???

Not std::cin itself, but operator>>, but yes, and that is exactly what is happening here.

Upvotes: 3

Christian Legge
Christian Legge

Reputation: 1043

Stream extractors (>>) are whitespace-delimited - when it reads, it stops when it hits any whitespace. The next time it's used, it begins reading from where it left off. If you want to only delimit on newlines, you can use cin.getline() instead.

EDIT: Correction from @Pete Becker.

Upvotes: 3

Related Questions