Below is the code for a function i'm using to input student data into an array of student structures. I want the loop to terminate when i has reached the limit (n) which is fine OR, and this is what i'm having trouble with, when a blank line is typed for a student name? Does anybody have any suggestions? The current method i'm using doesn't work (the if statement below ' cin.getline(pa[i].fullname, SLEN - 1); ')
int getinfo(student pa[], int n)
{
cout << "\nPlease enter student details:\n\n";
int i;
for (i = 0; i < n; i++)
{
cout << "Student " << (i + 1) << ": \n";
cout << " > Full name: ";
cin.getline(pa[i].fullname, SLEN - 1);
if (pa[i].fullname == NULL)
continue;
cout << " > Hobby: ";
cin.getline(pa[i].hobby, SLEN - 1);
cout << " > OOP Level: ";
cin >> pa[i].ooplevel;;
cin.get();
cout << endl;
}
cout << "--------------------------------------" << endl;
return i;
}
Better with string
and with an atomic loop:
std::string name, hobby, oop;
std::cout << "Name: ";
if (!(std::getline(std::cin, name)) { break; }
std::cout << "Hobby: ";
if (!(std::getline(std::cin, hobby)) { break; }
std::cout << "OOP: ";
if (!(std::getline(std::cin, oop)) { break; }
// if we got here, everything succeeded.
pa[i].name = name; pa[i].hobby = hobby; pa[i].oop = oop;
// or better, pass a `std::vector<student> &`:
pa.push_back(student(name, hobby, oop));