以下是我用来将学生数据输入到学生结构数组中的函数的代码。我希望当我达到上限(n)时就可以终止循环,否则,或者当为学生姓名键入空行时,这就是我遇到的麻烦?有人有什么建议吗?我正在使用的当前方法不起作用(“ cin.getline(pa [i] .fullname,SLEN-1);下面的if语句”)
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;
}
最佳答案
使用string
和原子循环更好:
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));