Solved

How to flush cin for getline?

Posted on 2003-11-15
13
2,274 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
  • 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 

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

Free Tool: Site Down Detector

Helpful to verify reports of your own downtime, or to double check a downed website you are trying to access.

One of a set of tools we are providing to everyone as a way of saying thank you for being a part of the community.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

Suggested Solutions

Errors will happen. It is a fact of life for the programmer. How and when errors are detected have a great impact on quality and cost of a product. It is better to detect errors at compile time, when possible and practical. Errors that make their wa…
  Included as part of the C++ Standard Template Library (STL) is a collection of generic containers. Each of these containers serves a different purpose and has different pros and cons. It is often difficult to decide which container to use and …
The goal of the tutorial is to teach the user how to use functions in C++. The video will cover how to define functions, how to call functions and how to create functions prototypes. Microsoft Visual C++ 2010 Express will be used as a text editor an…
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.

730 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