odd behavior of cin.getline when it follows cin

This is a discussion on odd behavior of cin.getline when it follows cin within the C++ Programming forums, part of the General Programming Boards category; Im having a bit of a problem with this: Code: apstring String //String class that I gotta use char Hmm[8] ...

  1. #1
    Unregistered
    Guest

    Question odd behavior of cin.getline when it follows cin

    Im having a bit of a problem with this:

    Code:
    apstring String //String class that I gotta use
    char Hmm[8]
    cout << "Prompt - ";
    cin >> String;
    cout << "\nPrompt -";
    cin.getline(Hmm, 8)
    The program compiles fine, but when I run it, it accepts input to the first prompt but then, after displaying the second prompt, skips over the call of cin.getline immediately to the next statement. Hmm is left empty. It seems, however, to work if the cin.getline call is first.

    I'm confused.

  2. #2
    Registered User Citizen Bleys's Avatar
    Join Date
    Jan 2002
    Posts
    9
    There's crap in your buffer. Use cin.ignore() before your call to getline.

  3. #3
    Unregistered
    Guest
    we all try to avoid learning details when we don't have to, but sometimes there is no altrernatve. For better or worse, >> leaves the terminating white space in the input buffer. Since the next >> ignores any leading whitespace it isn't a big deal. Unfortunately, getline() doesn't ignore whitespace. If the newline char is the whitespace terminating the >> preceding the call to getline() then the first char getline will see is a newline char left over from the previous call to >> and if newline is the terminating char for getline() (newline is the defualt terminating char for getline() by the way) then nothing will be stored in the string used by getline(). Calling ignore() to clear the buffer after each call to >>, or at least after the last >> preceding a call to getline(), is the way to remedy the situation. ignore() defaults to ignoring one char which is a newline char, although you can override the defaults if you wish.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. C++ cin.getline help
    By zerlok in forum C++ Programming
    Replies: 3
    Last Post: 02-11-2008, 02:01 AM
  2. cin problem
    By mikahell in forum C++ Programming
    Replies: 12
    Last Post: 08-22-2006, 12:14 PM
  3. getline(function)??
    By dac in forum C++ Programming
    Replies: 7
    Last Post: 03-10-2006, 12:42 PM
  4. cin.getline and cin problems in a while loop
    By UnclePunker in forum C++ Programming
    Replies: 12
    Last Post: 05-07-2002, 10:43 AM
  5. Homework help
    By Jigsaw in forum C++ Programming
    Replies: 2
    Last Post: 03-06-2002, 05:56 PM

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