CPP 在读取结构数据时无限循环错误?



我想使用无限循环来读取 Person 结构(姓名、年龄、薪水)。我想在用户输入名称为"x"时中断循环。

#include <iostream>
#include <vector>
using namespace std;
struct Person
{
char name[50];
int age;
float salary;
};
int main(int argc, const char * argv[]) {
Person p1;
vector <Person> p1_vec;
while (true) {
cout << "Enter Full name or simply 'x' to exit: ";
cin.get(p1.name, 50);
bool next_entry = strcmp(p1.name,"x");
if (!next_entry) {
break;
}
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
p1_vec.push_back(p1);
}
}

您需要忽略读取salary输入后获得的新行字符:

cin >> p1.salary;

行为:

cin >> p1.salary;
cin.ignore(1, 'n');

将使代码停止到此:

cin.get(p1.name, 50);

并等待其他用户输入!

cin状态需要在阅读后清除,请尝试如下操作:

cin.clear();
cin.ignore(std::numeric_limits<streamsize>::max(), 'n');

例如(取决于所需的容错量)

while (true) 
{
cout << "Enter Full name or simply 'x' to exit: ";
cin.get(p1.name, 50);
cin.clear();
auto equal = strcmp(p1.name, "x")==0;
if (equal)
{
break;
}
cout << "Enter age: ";
cin >> p1.age;
cin.clear();
cout << "Enter salary: ";
cin >> p1.salary;
p1_vec.push_back(p1);
cin.clear();
cin.ignore(std::numeric_limits<streamsize>::max(), 'n');
}

cin.get(p1.name, 50)不消耗输入工资后仍保留在输入缓冲区中的n;因此它跳过输入并将值留空。

cin >> p1.name,它应该可以正常工作。

从输入缓冲区获取数据后,应将其清除。

int main(int argc, const char * argv[]) {
Person p1;
vector <Person> p1_vec;
while (true) {
cout << "Enter Full name or simply 'x' to exit: ";
cin.get(p1.name, 50);
bool next_entry = strcmp(p1.name,"x");
if (!next_entry) {
break;
}
cout << "Enter age: ";
cin >> p1.age;
cout << "Enter salary: ";
cin >> p1.salary;
p1_vec.push_back(p1);
cin.clear();
cin.ignore();
}
}

最新更新