Advertisement
If you have a new account but are having problems posting or verifying your account, please email us on hello@boards.ie for help. Thanks :)
Hello all! Please ensure that you are posting a new thread or question in the appropriate forum. The Feedback forum is overwhelmed with questions that are having to be moved elsewhere. If you need help to verify your account contact hello@boards.ie

getline() acting strangely in VC++

Options
  • 16-11-2003 2:21pm
    #1
    Closed Accounts Posts: 1,669 ✭✭✭


    getline() is doing something strange in my code when I call it for a second time in VC++ 6. The (abridged) code:
    string buffer;
    int value;
    cout << "\n\nEnter data: ";
    getline(cin, buffer);
    cout << "\nEnter int value: ";
    cin >> value;
    cout << "\nXXX01: " << buffer;
    cout << "\n\nEnter data: ";
    getline(cin, buffer);
    cout << "\nXXX02: " << buffer;
    

    The output (italics indicate data entered at run time):
    Enter data: sfgsdfds

    Enter int value: 63424XXX

    XXX01: sfgsdfds

    Enter data:
    XXX02:XXX

    The problem is that the second time getline() is called it doesn't wait for the user to enter data but instead takes whatever characters are at the end of the int value entered by the user.

    If the user enters only a true integer:
    Enter int value: 63424

    Then the output will be:
    XXX02:


    What could be causing this?


Comments

  • Closed Accounts Posts: 1,669 ✭✭✭DMT


    It's ironic that after starting this thread after hours of fruitless googling that I almost immediately find the solution myself.

    For those who encounter this problem in the future here's what's happening and how to fix it:
    From http://forums.devshed.com/archive/42/2003/4/1/57125

    Another "bug"(it's actually due to the way streams work) that comes up all the time also has to do with getline(). If you do something like this: cin>>var; and then later: cin.getline(text, maxlength); The program will apparently skip the second line of code. What actually happens is the first cin leaves the \n in the stream that the user entered, and then when cin.getline() executes it doesn't have to wait for user input because there's still something in the stream. So, it starts reading from the stream, and since \n is the default delimiter for getline(), it terminates reading from the stream and execution continues. The problem and fix are described here: http://www.augustcouncil.com/~tgibson/tutorial/iotips.html Both those problems should be discussed in every beginning C++ book, yet they are ignored causing hours of frustration for so many people.

    The solution (found at the above link was to add cin.ignore(); before the second getline() call:
    cin.ignore();
    getline(cin, buffer);
    


Advertisement