C++ getline/string need to input twice? arg!

michaelh20

Senior member
Sep 4, 2000
482
0
0
I fixed the following by getting a string and getting the first char of the string... still is there a way to flush cin if I wanted to?


Also does anyone know of a good string tokenizer for c++ ? I like to input a bunch of numbers on a line and string tokenize it.. :)
===========================================

I have the following code, which is supposed to get a line
and stick it in a string. There's a basic menu before this
that cin's a char to choose a menu option. What happens is I have to input the string twice or else it doesn't get anything at all. Does the cin of a char leave the rest of the input to muck up any other input? Or is there a way to flush cin so it doesn't keep stuff around?

the main menu inputs a char and then does something like:

switch(charChoice){
case 'h':
printMenu();
break;

case 'a':
addEntry();
break;


void addABunch() {
cout << (&quot;Gimme a bunch of numbers : &quot;);
string input;

getline(cin,input);
getline(cin,input); // had to do it twice...


cout << &quot;You gave me : &quot; << input << &quot;\n&quot;;
}
 

Nevyn522

Senior member
Aug 11, 2000
208
0
0
Ah, I've seen this problem.

I don't remember exactly what caused it, but best guess is that the buffer isn't flushed, so your first input is actually the &quot;enter&quot; from the previous user input... I know there's a way to flush buffers, but I don't remember what it is.

If it's an option, you might want to look into using &quot;getch()&quot; ( I think that's it ) -- it will take a single character input only, but might be good enough for your purposes.

Good luck!
Andrew
 

2ndDawn

Junior Member
Jan 8, 2001
14
0
0
That's pretty much the best thing you can do...all getch() does is it pauses the program waiting for a button from the keyboard to be pressed.
 

PierreJ

Junior Member
Jan 14, 2001
2
0
0


<< getline(cin,input); >>



why are you using cin with the getline function??

You dont have to do all that

Here is the code

KISS - Keep It Small Simple

Updated Code:

void addABunch() {
string input;
cout << &quot;Gimme a bunch of numbers : &quot;;
cin >> input;
cout << &quot;You gave me : &quot; << input << endl;
}

Hope that helps