1

I am currently learning how to write a code that prompts the user to define how many players and rounds they want in a dice game, with the additional goal to output the results of both into a file. A couple of resources I have seen have suggested when defining the string variable, you want a secondary string for the sole purpose to "gobble newlines."

Here is the snippet of the code I was looking at:

int main()
{
    int nPlayers, nRounds, score;
    **string name, dummy;**
    cout <<"Enter number of players: ";
    cin >> nPlayers;
    cout << "Enter number of rounds: ";
    cin >> nRounds;
    **getline (cin, dummy); // gobble up newline**
    ofstream ofs ("scores.txt");
    ofs << nPlayers << " " << nRounds << endl;

My question is based around the two lines denoted with double asterisks. Why the need to write a string like this?

Rovalias
  • 13
  • 3
  • Because otherwise it is not consumed and the next loop will get it instead of the next value, if there is a next loop. – user207421 Oct 18 '21 at 05:39
  • It means explicitly read the extra newline at the end of the input into dummy. To gobble up = to eat up and let it dissapear so it is not a technical or C++ word, just human speech :) – Pepijn Kramer Oct 18 '21 at 05:41
  • @PepijnKramer: Thank you both for responding. I feel a bit silly that I didn't pick up on how straight forward and literal it was. I for some reason thought gobble was slang for a process that was commonly used or something, since it is such an infrequent word to come up and to see it used in three different areas describing the same thing? Yeah, I definitely wanted to double check that. Thank you both for your input! – Rovalias Oct 18 '21 at 05:54

1 Answers1

0

Many input streams have extra newline characters between inputs. "Gobble up a newline" is to get rid of those to get the correct output.

For example:

5 //number of inputs
//empty newline character
89 //first input value
...

The dummy variable is used to store it since it is not of much use to store a newline character.

ouflak
  • 2,458
  • 10
  • 44
  • 49
The Mist
  • 16
  • 4
  • 1
    I feel a bit silly, I thought gobble was in reference to a special process or something. It didn't dawn on me that it literally meant what it said. Thank you for your answer on the matter, it definitely cleared it up! – Rovalias Oct 18 '21 at 05:55