我正在尝试将一些值分配给来自cin
.
如何实现 while 循环在输入特定单词后立即中断,例如end
?在我的示例中,仅当我将此单词输入为“年龄”时它才会中断,因此仅在循环结束时。如果我在开头输入它(作为“名称”),它就会继续。
#include <iostream>
#include <vector>
using namespace std;
struct person {
string name;
string age;
};
int main() {
vector<person> myPerson;
string text;
while(text != "end") {
person tempPerson;
cout << "Name:" << endl;
cin >> text;
tempPerson.name = text;
cout << "Age:" << endl;
cin >> text;
tempPerson.age = text;
myPerson.push_back(tempPerson);
}
for(int i=0; i<myPerson.size(); i++) {
cout << "Person No. " << i << ": " << endl;
cout << "Name: " << myPerson[i].name << endl;
cout << "Age: " << myPerson[i].age << endl;
}
return 0;
}