Solved

How to flush cin for getline?

Posted on 2003-11-15
13
2,245 Views
Last Modified: 2008-01-09
Hello, i'm trying to code up a little command interpreter for the terminal.

basically it's like this:

while(notDone)
{
      getline(cin, input);
      istringstream instr(input);
      switch(..
                ......
}

Suppose the first command that I enter is "create blah," then I hit enter.
The command is executed.

NOW i just hit enter again without typing anything else, and it executes the command again because the input was not flushed.

Any help? Thanks.
0
Comment
Question by:lapchern
  • 5
  • 3
  • 3
  • +1
13 Comments
 
LVL 33

Expert Comment

by:hongjun
ID: 9753626
try this

fflush(stdin);


hongjun
0
 

Author Comment

by:lapchern
ID: 9753639
Thanks for the response but I got no luck. I plugged fflush(stdin); at the end of my loop. Here's a sample output to show what I'm talking about
-------------------------------------
begin input
cr a //typed in this command
a created.
[hit enter]
Duplicate file name.
[hit enter]
Duplicate file name.
[hit enter]
Duplicate file name.
cr b //typed in this command
b created.
-------------------------------------
it says duplicate file name because it invisibly executes "cr a" over and over again unless i explictly  type in a new command.
0
 
LVL 33

Expert Comment

by:hongjun
ID: 9753640
make sure you have got
   fflush(stdin);
before getline statement.

hongjun
0
 

Author Comment

by:lapchern
ID: 9753642
Here's an actual chunk of my code

      while (notDone)
      {
            //arg1,arg2,arg3,arg4,arg5,arg6 = "";
            
            getline(cin, input);

            istringstream instr(input);
            arg6 = "";
            instr >> arg1 >> arg2 >> arg3 >> arg4 >> arg5 >> arg6;
                           ...begin interpretation
                              .........
                 }
0
 
LVL 33

Expert Comment

by:hongjun
ID: 9753644
try something like this

while (notDone)
     {
          fflush(stdin);
          //arg1,arg2,arg3,arg4,arg5,arg6 = "";
         
          getline(cin, input);

          istringstream instr(input);



hongjun
0
 

Author Comment

by:lapchern
ID: 9753656
yeah i just tried that, still no good =(.

here are the things i included

#include "stdafx.h"
#include <string>
using namespace std;
#include <sstream>


if that helps
0
How to run any project with ease

Manage projects of all sizes how you want. Great for personal to-do lists, project milestones, team priorities and launch plans.
- Combine task lists, docs, spreadsheets, and chat in one
- View and edit from mobile/offline
- Cut down on emails

 
LVL 11

Expert Comment

by:bcladd
ID: 9753732
The original poster and hongjun are using the word "flush" to cross purposes.

hongjun is trying to flush the input stream using standard file flushing routines. In this context, flushing means to complete any buffered I/O operations. Flushing is typically used on output in anicipation of input from the user (cin and cout are related in this way by default; before cin blocks for input, cout is flushed to make sure your prompt is visible to the user).

The original question says that the second time through their command processing loop, if an empty string is provided as input, the input value is not changed by getline. lapchern wants to "flush" the previous value from the input value. This actually has nothing to do with cin and everything to do with the variable holding the command. My quick and dity solution is to insert the line

    input = "";

right before the getline in the loop. Clears out the historical values for a fairly low cost.

Give it a shot.

-bcl
0
 
LVL 19

Expert Comment

by:mrwad99
ID: 9755177
when using getline, it is important to remember that the function will read into 'input' until it hits the default terminator, which is '\n'.  It will then throw away the '\n' from the 'input' thereby leaving it in the buffer.

It looks like when you are reading in the second line, the '\n' is still left over so the getline function assumes this is what you have entered.  Get rid of the stored '\n' by using cin.ignore(strlen(input), '\n').

This will hence remove the '\n' from the input.

Also something that will benefit you if you use MSVC++ 6.0 or less:

http://people.msoe.edu/~welch/courses/string.html

A bug in the getline method.

Scary !

0
 
LVL 11

Expert Comment

by:bcladd
ID: 9755223
getline(istream, string, char) will read up to the given terminator character. As mrwad99 notes, the default value for the terminator is '\n'. mrwad99 is not correct, however, on what happens to the terminator character. It is NOT copied into the string but it IS consumed from the input stream. Thus it reads up to and INCLUDING the terminator from the input stream and puts everything up to and NOT INCLUDING the terminator into the string.

VC++ isn't the only compiler to have getline problems. Borland BCC5.5 before patch level 1 (or 2, I can't recall) counted the appended '\0' in the length of a string read using getline. Lots of fun to figure out what was "wrong" with the length member after that.

-bcl
0
 
LVL 19

Expert Comment

by:mrwad99
ID: 9755267
bcladd,

Thanks for that fact about the Borland compiler.  I dont use it but it is reassuring to hear that Microsoft is not the only one with problems !

Now, about the getline function:

On goes my dunce hat !

I mistook the internals of getline() with those of get(); the *latter* leaves the '\n' in the input stream, the former does *not* but throws it away.

<Sits in corner looking sheepish>
0
 

Author Comment

by:lapchern
ID: 9756441
i plugged in some stuff at the top and i still have no luck =(. it really boggles the mind.

            input = "";
            arg1,arg2,arg3,arg4,arg5,arg6 = "";

            getline(cin, input);
            istringstream instr(input);
            arg6 = "";
            instr >> arg1 >> arg2 >> arg3 >> arg4 >> arg5 >> arg6;


i also tried pluggin in cin.ignore(strlen(input), '\n'). at the top but i get a cannot convert std:string to char* error.

by the way i'm using visual c++ .net.
0
 
LVL 11

Accepted Solution

by:
bcladd earned 20 total points
ID: 9756507
I can fix the final error: use c_str():
   strlen(input.c_str()) is the legal call to strlen. Better would be to use the length() function on the string: input.length()

Note that arg1...arg5 are NOT cleared before you go through the istringstream. I'll bet arg6 IS cleared. Other option is to have an if on input == "" and never parse the empty string.

-bcl
0
 

Author Comment

by:lapchern
ID: 9756670
damn what a dumb mistake i made...i thought that line would work!! that fixed it!
0

Featured Post

How your wiki can always stay up-to-date

Quip doubles as a “living” wiki and a project management tool that evolves with your organization. As you finish projects in Quip, the work remains, easily accessible to all team members, new and old.
- Increase transparency
- Onboard new hires faster
- Access from mobile/offline

Join & Write a Comment

Suggested Solutions

Templates For Beginners Or How To Encourage The Compiler To Work For You Introduction This tutorial is targeted at the reader who is, perhaps, familiar with the basics of C++ but would prefer a little slower introduction to the more ad…
This article will show you some of the more useful Standard Template Library (STL) algorithms through the use of working examples.  You will learn about how these algorithms fit into the STL architecture, how they work with STL containers, and why t…
The goal of the video will be to teach the user the difference and consequence of passing data by value vs passing data by reference in C++. An example of passing data by value as well as an example of passing data by reference will be be given. Bot…
The viewer will learn how to pass data into a function in C++. This is one step further in using functions. Instead of only printing text onto the console, the function will be able to perform calculations with argumentents given by the user.

762 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

23 Experts available now in Live!

Get 1:1 Help Now