Search code examples
c++arraysstructgetline

getline does not take any input


I need to use getline to store whole line when user enters name and surname. When I run the program, it passes row of getline(cin,st[i].name); I mean the input function does not work, it skips next cin which is for "score".

struct Student {
    string name;
    int score;
    char grade;
};

void main() {
    int SIZE;
    cout << " How many students are you going to add ? ";
    cin >> SIZE;
    Student* st = new Student[SIZE]; // user determines size of array.
    int i;
    for (i = 0; i < SIZE; i++)
    {   
        if (st[i].name.empty()) // if array list of name is empty, take input.
        {
            cout << "name and surname : ";
            //cin >> st[i].name;
            getline(cin, st[i].name);
        }
        cout << "Score : ";
        cin >> st[i].score; // take quiz score from user.

-- I did not put whole main function.

So when l run the program, back screen is shown like this

Is there any other way to get input for name ?


Solution

  • After cin >> SIZE;, the trailing newline is still kept in standard input.

    You need cin.ignore() to skip the remaining newline character so the later getline() could get the value.