Sign in to follow this  

Question about cin.

Recommended Posts

hola, I was wondering, after you get a users input, is it a good idea to place cin.ignore after ever cin? Heres an example:
int main()
    int favNum;
    int favNum2;

    std::cout << "Whats your favorite number? ";
    std::cin >> favNum;

    std::cout << "\nWhats your 2nd favorite number? ";
    std::cin >> favNum2;

    std::cout << "\n\nYour favorite number is: " << favNum
              << "\nYour 2nd Favorite number is: " << favNum2;

    return 0;
Thanks for any help. :D

Share this post

Link to post
Share on other sites
It is not needed.

cin.ignore is only useful if the input buffer contains data you don't want to read in. It is very useful, for instance, when you use a cin.get or cin.getline.

The stream operator (>>) ignores whitespace (spaces, tabs, newlines). so when you do:

std::cin >> some_number;

the whitespace after the number is left on the stream. The next time you use the stream operator this will be disreguarded. If you use cin.get, however it will not. It is situations like this that cin.ignore becomes useful.

Share this post

Link to post
Share on other sites
The problem arises when you have input such as this:

"2 2"

cin is only going to grab the first 2. The second two is going to be left in the buffer and it's going to cause problems.

This is a great faq about cin and the way it operates. It directly corelates to your question. Read through it, it should clear up any misunderstanding.

[Edited by - Run_The_Shadows on May 1, 2006 1:16:22 PM]

Share this post

Link to post
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now

Sign in to follow this