Thread: Problem With std::getline And C++

  1. #1
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348

    Problem With std::getline And C++

    Hi,
    I find there is a slight inconvenience with the std::getline function in C++. Here is an example:

    -----------------------------------------------------------
    #include <iostream>
    using std::cin;
    using std::cout;
    using std::endl;
    using std::getline;

    #include <string>
    using std::string;

    int main()
    {
    string strTemp;

    cout << "Enter a sentence: ";
    getline(cin, strTemp);

    cout << "\nYou entered: "
    << strTemp << endl;

    return 0;
    }

    -----------------------------------------------------

    If you run the code above, and hopefully I did not leave anything out, out will find that after you entered a sentence and press Enter, the "cursor" will go to the next line, but the program does not move onto "You have entered: " until you press Enter the second time. In other words, I have had problems with the getline function in term of having to press Enter twice to get it to move onto the next algorithm.

    I have tried for example:

    getline(cin, strTemp, '\n');

    It has the same effect.

    Is there a way to get around having to press Enter twice?

    Thanks,
    Kuphryn

  2. #2
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    Worked for me. What compiler are you using?
    zen

  3. #3
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348
    I am using VC++ 6 under XP.

    Kuphryn

  4. #4
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    Thought so, there's a fix here.
    zen

  5. #5
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348
    Interesting. Thanks.

    I looked in string.h, but I could not find the line that article mentioned.

    Kuphryn

  6. #6
    of Zen Hall zen's Avatar
    Join Date
    Aug 2001
    Posts
    1,007
    string.h is the C string standard library header. STL string is just string (without the h extension).
    zen

  7. #7
    Registered User
    Join Date
    Nov 2001
    Posts
    1,348
    Oh oh! Thanks!

    It works great.

    Thanks again.

    Kuphryn

    P.S. VC++ 6 is beginning to look pretty BAD for me.

  8. #8
    _B-L-U-E_ Betazep's Avatar
    Join Date
    Aug 2001
    Posts
    1,412
    Move this to the FAQ. Good stuff.
    Blue

Popular pages Recent additions subscribe to a feed