cin

From: Martijn Mulder (i_at_m)
Date: 02/22/05


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;
}



Relevant Pages

  • Re: cin
    ... >I try to read one character from cin and use it as ... > I am looking for a way to clear cin, ... > start with 'fresh' input inside the switch statement. ... You want cin.ignore(int # max of characters to ignore/flush, ...
    (alt.comp.lang.learn.c-cpp)
  • Re: Lots of design issues needed.
    ... One possibility would be to replace the switch statement with an array ... > int showMenu() ... > int binarySearch(VPerson a, const string& x, const compare comp) const ...
    (alt.comp.lang.learn.c-cpp)
  • Re: member references
    ... then the next string would be the member name and sub member names etc. ... then use reflection to set/get the value. ... If you have a situation in which you think a switch statement does make sense, then rather than a plain index, you should probably use an enumeration. ... Why not just post a code sample that illustrates the basic idea. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: switch statement with the string being tested
    ... I have about 50 string values that can be in a string ... The switch statement seems to be a better choice then the ... int func; ... Visit http://www.ecomstation.de the home of german eComStation ...
    (comp.lang.c)
  • Re: Help needed in solving C-errors in Linux (gcc)
    ... > When i tried to compile this test driver for an actual conversion library ... "multi-character character constant". ... you can't use a string in a switch statement. ...
    (comp.os.linux.development.apps)