Home > Enterprise >  Program skips getline [duplicate]
Program skips getline [duplicate]

Time:10-06

The input is skipped over. This is such a simple program but I cant figure out why it would skip this.

#include <iostream>
#include <string>
using namespace std;
int main()
{
    int repeat;
    string message;

    cout<<"Computer Punishment"<<endl;
    cout<<"-----------------------"<<endl;
    cout<<"Repititions? ";
    cin>>repeat;
    cout<<"Message? ";
    getline(cin, message);
    for(int i=0;i<repeat;i  )
    {
        cout<<message<<endl;
    }
}

CodePudding user response:

    int repeat;

    [ ...]

    cin>>repeat;
    [...]
    getline(cin, message);

When you enter the value for repeat, you press the enter key. Then the digits you (presumably) typed in get read to get the value for repeat. But the new-line you entered remains in the input buffer.

Then when you call getline, it looks at the input buffer, and reads data until it find a new-line, at which point it stops and returns all the data it found before the new-line--which (in this case) is likely to be nothing, so you'll read in an empty string.

To test that this is what's actually happening, when it asks for the repetition count, you can type in something like: 12 some stringenter. Then the 12 will be read as the value for repeat, and some string as the string, which will then be printed back out 12 times.

CodePudding user response:

This issue exists because of cin and getline behaviour.

When you are reading first number, input stream looks like this:

before cin:
  2\n
  ^

after cin:
  2\n
    ^

cin reads only required number and then the caret points to \n symbol.

So getline by default reading from curent caret position to \n and in this example it reads an empty string. So you need to read this \n before getline (this is only one of the solutions) and then your code will work:

#include <iostream>
#include <string>
using namespace std;
int main()
{
    int repeat;
    string message;

    cout<<"Computer Punishment"<<endl;
    cout<<"-----------------------"<<endl;
    cout<<"Repititions? ";
    cin>>repeat;
    cout<<"Message? ";
    
    cin.get() // get '\n' symbol
    
    getline(cin, message);
    for(int i=0;i<repeat;i  )
    {
        cout<<message<<endl;
    }
}
  • Related