所以当我在选项1中输入我的输入后,我选择继续。我的输入信息在选择选项2时消失了。我刚开始我的编程课程,所以请给我很多建议。这是这里的输出输入图像描述
struct Human
{
string name;
string foods;
string date;
};
char option;
int main()
{
do
{
int user;
cout << "You" <<endl;
cout << "\nChoose one from the menu below" <<endl;
cout << "1 Enter information" <<endl;
cout << "2 See information stored" <<endl;
cout << "\nEnter your option" <<endl;
cin >> user;
Human me;
switch(user)
{
case 1:
{
cin.ignore(100, '\n');
cout << "\nEnter your name: ";
getline(cin, me.name, '\n');
cout << "Enter your favorite foods: ";
getline(cin, me.foods, '\n');
cout << "Enter your birthday: ";
getline(cin, me.date, '\n');
break;
}
case 2:
{
cin.ignore(100, '\n');
cout << "Your name is: " << me.name<<endl;
cout << "Your favorite foods are: " <<me.foods<<endl;
cout << "Your birthday is: " <<me.date<<endl;
break;
}
}
cout << "\nDo you wish to continue?" <<endl;
cout << "Enter 'y' to continue and 'n' to exit" <<endl;
cout << "Your choice:";
cin >> option;
}while(option == 'y');
return 0;
}
在do-while循环的每次迭代中都创建一个新的human me;
。当您在一次迭代中读取ME
的输入时,下一次迭代中的ME
将不会知道这一点。
阅读“作用域”,将声明human me;
移到循环之外可能会达到您所期望的效果。