1

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 ?

timrau
  • 22,578
  • 4
  • 51
  • 64
Alican Balik
  • 1,284
  • 1
  • 8
  • 22

1 Answers1

4

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.

timrau
  • 22,578
  • 4
  • 51
  • 64
  • Thank you sir. It works but I have one more question. Should I also use cin.clear() ? or do I need to write cin.ignore(1000, '\n') instead of () ? – Alican Balik Oct 25 '15 at 15:38
  • Well, you could write `cin.ignore(numeric_limits::max(), '\n');` after you `#include `. That will successfully ignore as much characters are left in the stream. – DeiDei Oct 25 '15 at 16:12