problem with cin

This is a discussion on problem with cin within the C++ Programming forums, part of the General Programming Boards category; Hi, I am reading input from standard input using cin. I want to be able to read in newlines. The ...

  1. #1
    Registered User
    Join Date
    Nov 2005
    Posts
    38

    problem with cin

    Hi,
    I am reading input from standard input using cin. I want to be able to read in newlines. The problem is that sometimes there is other stuff in the cin buffer that may have been left over. I dont want to read this in. Is there anyway that I can flush out the cin buffer to be sure that there is nothing in it. I thought that maybe I could use peek to see if there is something there and if there is then read it. But it doesnt seem to be working. I am using something like the following:

    Code:
    if(cin.peek() != EOF)
    {
        cin.ignore(100, '\n');
    }
    char choice;
    cin.get(choice);
    Can someone help me with this?
    Thanks
    Mark

  2. #2
    Registered User
    Join Date
    Feb 2006
    Posts
    312
    You don't have to use peek in order to call cin.ignore() - if the buffer is empty, ignore() will have no effect.

  3. #3
    Registered User
    Join Date
    Jan 2005
    Posts
    7,344
    Actually, if the buffer is empty, the ignore() will wait for the user to type something and press enter.

    Since the user has to hit enter before any data is sent from the console to the input stream, you can usually figure out whether there is anything left in the stream that would allow a call to ignore(). How you do that depends on what cin functions you are using to read in the previous input.

    For example, if you are using cin >>, then there will always be at least a '\n' in the stream, so you can call the ignore safely. If you are using get you can check the value gotten to see if it is '\n', and if it isn't then you can call the ignore safely. If you are using getline, then no matter what you won't need the ignore because the newline is automatically discarded. If you are mixing the ones above, then you should deal with any potential extra characters and the trailing newline when you do the read instead of later before the next read.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with cin. Please help me.
    By Antigloss in forum C++ Programming
    Replies: 17
    Last Post: 06-06-2005, 10:50 AM
  2. Input File HELP, weird problem
    By gravity-1 in forum C++ Programming
    Replies: 5
    Last Post: 03-29-2005, 08:43 PM
  3. half ADT (nested struct) problem...
    By CyC|OpS in forum C Programming
    Replies: 1
    Last Post: 10-26-2002, 09:37 AM
  4. binary tree problem - help needed
    By sanju in forum C Programming
    Replies: 4
    Last Post: 10-16-2002, 06:18 AM
  5. Problem with cin
    By ErionD in forum C++ Programming
    Replies: 3
    Last Post: 02-19-2002, 11:27 AM

1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21