Monday, February 23, 2009

Clean up after cin (C++)

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.
Author :Major_Small

0 nhận xét:

Post a Comment