• We’re currently investigating an issue related to the forum theme and styling that is impacting page layout and visual formatting. The problem has been identified, and we are actively working on a resolution. There is no impact to user data or functionality, this is strictly a front-end display issue. We’ll post an update once the fix has been deployed. Thanks for your patience while we get this sorted.

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

michaelh20

Senior member
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;;
}
 
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
 
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.
 


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


 
Back
Top