clean up after cin (C++)

This tip submitted by Major_Small on 2005-01-30 02:25:49. It has been viewed 82104 times.
Rating of 5.7 with 433 votes



It's a good idea to follow cin with cin.get() or cin.ignore() because cin can leave a terminating character in the stream, which could case small problems with your code. for example:


#include<iostream>



int main()

{

    int age;

    

    std::cout<<"Enter your age: ";

    std::cin>>age;

    std::cout<<"You entered "<<age<<std::endl;

    

    std::cin.get();

    return 0;

}


That code exits right after printing the age. The program 'skips' right over where it should 'pause' for the user to press Enter. This is bad because the user never gets to see what is being written to the screen after they enter the age*. The following code, however, works as intended:


#include<iostream>



int main()

{

    int age;

    

    std::cout<<"Enter your age: ";

    std::cin>>age;

    std::cin.ignore();  //remove the terminating character

    std::cout<<"You entered "<<age<<std::endl;

    

    std::cin.get();

    return 0;

}


As you can see, there is a new line, where cin.ignore() is used. This will take in the character that cin left in the stream.


*Some compilers will put a pause after the program runs. Those compilers will not demonstrate this point well at all.



More tips

Help your fellow programmers! Add a tip!