Jump to content
  • Advertisement
Sign in to follow this  

Question about cin.

This topic is 4492 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

If you intended to correct an error in the post then please contact us.

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
Sign in to follow this  

  • Advertisement

Important Information

By using GameDev.net, you agree to our community Guidelines, Terms of Use, and Privacy Policy.

We are the game development community.

Whether you are an indie, hobbyist, AAA developer, or just trying to learn, GameDev.net is the place for you to learn, share, and connect with the games industry. Learn more About Us or sign up!

Sign me up!