Advertisement

Using cin

Started by October 28, 2001 12:05 AM
2 comments, last by pizza box 23 years ago
When using cin to get one value from the user, often times they can enter more than one value and my program runs more than once. Is there a way to get the first value from cin then clear the rest after them?
cin.flush()?

[Resist Windows XP''s Invasive Production Activation Technology!]
Advertisement
quote: Original post by Sethius
When using cin to get one value from the user, often times they can enter more than one value and my program runs more than once. Is there a way to get the first value from cin then clear the rest after them?

Assuming that you mean the user enters two values seperated by a space, for example, you might want to parse the input from cin to ensure it''s a single value.

istream objects don''t support flush(), AFAIK.

Here''s little example:
int main(...){  string input;  cout << "Please enter only ONE value: ";  cin >> input;  int i = input.find_first_not_of(" ", 0); // finds first non-space character  int j = input.find_first_not_of(" ", i); // finds next  string str = input.substr(i, (j - i));// you could replace all the string manipulation by// str = strtok(input) if you used C-style strings (char *)  cout << "The value you entered was " << str << endl;} 
Uhmm....operator >> for cin only reads up to the first whitespace anyway. A good practice when using >> for console input is to use the ws manipulator to eat up whitespace:
  cout << "Enter a number: ";int number;cin >> number >> ws;  


"A society without religion is like a crazed psychopath without a loaded .45"
--AnkhSVN - A Visual Studio .NET Addin for the Subversion version control system.[Project site] [IRC channel] [Blog]

This topic is closed to new replies.

Advertisement