cin
From: Martijn Mulder (i_at_m)
Date: 02/22/05
- Next message: Marshall Cline: "C++ FAQ"
- Previous message: Bart van Ingen Schenau: "Re: Event handling?"
- Next in thread: Dietmar Kuehl: "Re: cin"
- Reply: Dietmar Kuehl: "Re: cin"
- Reply: Peter van der Goes: "Re: cin"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Date: Tue, 22 Feb 2005 23:09:33 +0100
I try to read one character from cin and use it as
a condition in a switch statement. However, after
pressing <Enter>, control falls through the switch.
In the little program below, there are 2 options.
Type a or b first. Then type a string. When I type 'a',
then <Enter>, the program outputs:
You typed 'a' first and then you typed''
However, when I type something like 'awhat a day'
at the prompt, the output is:
You typed 'a' first and then you typed 'what a day'
I am looking for a way to clear cin, so that I can
start with 'fresh' input inside the switch statement.
#include<iostream>
#include<string>
int main()
{
char a;
string s;
cout<<"\nType a or b, type <Enter> to accept, then type a string"<<endl;
cin>>a;
cin.clear(); //doesn't solve it
cin.sync(); //doesn't solve it either
switch(a)
{
case 'a':getline(cin,s);break;
case 'b':getline(cin,s);break;
}
cout<<"\nYou typed '"<<a<<"' first and then you typed '"<<s<<'\'';
return 0;
}
- Next message: Marshall Cline: "C++ FAQ"
- Previous message: Bart van Ingen Schenau: "Re: Event handling?"
- Next in thread: Dietmar Kuehl: "Re: cin"
- Reply: Dietmar Kuehl: "Re: cin"
- Reply: Peter van der Goes: "Re: cin"
- Messages sorted by: [ date ] [ thread ] [ subject ] [ author ]
Relevant Pages
|