Trouble with getline() (<string>)

Hello, I am programming a relatively advanced Tic-Tac-Toe game, and I am having trouble with using the getline() command in the <string> library.
It is not a big deal that this is fixed, as the game can function without it, but I thought it would be nice if the player could enter both his first and last name. There is no error that occurs, but when compiled it simply skips over the user input and jumps straight to the return.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  string OnePlayerGame()
{
    NumberOfPlayers = 1;
    cout << "You have selected a one player game, your opponent will be the computer.\n\nEnter Your Player Name: ";
    std::getline(cin, PlayerOneName);
    return PlayerOneName;
}
string TwoPlayerGame()
{
    NumberOfPlayers = 2;
    cout << "You have selected a two player game, your opponent will be another human.\n\nEnter Player One Name: ";
    std::getline(cin, PlayerOneName);
    cout << "\nEnter Player Two Name: ";
    std::getline(cin, PlayerTwoName);
    return (PlayerOneName, PlayerTwoName);
}

These are the two string classes for the two different game types. If you need the rest of the code, just ask.
At any point before you call OnePlayerGame() or TwoPlayerGame(), do you have something like cin >> FOO? That instruction will leave a newline character in the buffer, which the getline calls will catch. That will make it appear as if it were skipped over.

Random Note:
Line 15 will only return PlayerTwoName. You cannot return multiple values like that.
you need a character delimiter i believe is what it is called.

std::getline( std::cin, p1name, '\n' );

that will take the entire input until a new line character is reached.
@Daleth: Yes I do, and it is essential to the code. Is there any way to work around this, so that the newline character is removed from the buffer?
@Paoletti301: I tried this, and it did not work.
You can get rid of unwanted characters from the input buffer by either:
1
2
cin.ignore();          // one character ignored
cin.ignore(100, '\n'); // ignore up to 100 characters, or until newline is found 
Last edited on
^^
Thank you so much, Chervil!
This is exactly the solution I was looking for.
@Paoletti301: I tried this, and it did not work.


it works fine for me.

the problem probably stems from, as daleth said, you trying to return two pieces of data from a function at line 15, which you cant do
@Paoletti: getline() by default uses a delim of '\n' so specifying like you suggesting wouldn't affect the result. The issue was as result of what Daleth said about cin>> leaving trailing whitespace like newlines in the buffer.
Topic archived. No new replies allowed.