Hello, I am doing a lab in OOP (C ++), the goal: to write information about a student to a file using structures. Here is a piece of code where this operation is performed:

struct student { string name; string address; string number; }; string n, a, nu; student KI[30]; void Addinfo(student* KI) { cout << endl; cout << "Имя и фамилия студента" << endl; getline(cin, n); cout << "Домашний адресс студента" << endl; getline(cin, a); cout << "Телефонный номер студента" << endl; cin >> nu; KI[0].name = n; KI[0].address = a; KI[0].number = nu; } void AddStudent() { ofstream infodat("INFO.txt", ios::app); if (infodat.fail()) cerr << "Ошибка открытия файла INFO.txt" << endl; else { Addinfo(KI); infodat.write((char*) &KI[0], sizeof(student)); infodat.close(); } infodat.close(); main(); } 

The problem is this: When I call a function 1 time, everything works fine, but when I call a function 2 times (without closing the program), the program skips the line:

 cout << "Имя и фамилия студента" << endl; getline(cin, n); 

And in the console this goes: enter image description here

Shifted from stackoverflow.com 11 Sep '16 at 10:25 .

The question was originally posted on the site for professional and enthusiast programmers.

    2 answers 2

    Read all with getline . In this case, enter also read from the buffer.
    If read through cin >> nu , then enter ignored and read the next time getline started. And you get an empty string.

     void Addinfo(student *KI) { cout << endl; cout << "Имя и фамилия студента" << endl; getline(cin, n); cout << "Домашний адресс студента" << endl; getline(cin, a); cout << "Телефонный номер студента" << endl; getline(cin, nu); KI[0].name = n; KI[0].address = a; KI[0].number = nu; } 
    • Thank you for your help. - nait123321
    • The issue is resolved. Tick ​​one of the answers. - Sergey Tyulenev

    Flush the buffer. After cin >> nu; \n remains in it, and upon subsequent reading of getline empty line is read.

    • Thank you for your help. - nait123321