c++ - 我想运行一个是/否循环来使用向量输入学生列表并显示它,直到用户选择输入学生姓名
问题描述
这是我的代码,我不明白我做错了什么。每次按下“y”或“Y”后,输入字符串不会连续工作。相反,它在第一次输入字符串后一次又一次地显示问题消息。
int main(){
vector<string> v;
int count=0;
bool value=true;
string s;
char ch;
cout<<"Start entering the name of the students :- "<<endl;
while(value){
getline(cin,s);
v.push_back(s);
count++;
cout<<"Do you want to Enter one more name :- Press 'y/Y' to continue or 'n/N' to end -> ";
cin>>ch;
if(ch=='n'||ch=='N') value=false;
}
cout<<"So, there are total "<<count<<" number of students and their names are :-"<<endl;
for(auto x:v) cout<<x<<endl;
return 0;
}
解决方案
我认为,当我们输入数值时,我们按下回车键,因此回车键也进入输入,但 cin 在输入之前取值并将输入留在流中,所以当我们获得下一个输入时进入并且我们的输入被跳过(空)这导致了这个问题。
所以我们应该总是使用 cin.ignore(); 在每个整数输入之后。其他数字输入可能会发生同样的情况。在您的情况下,它发生在 char 输入上,这也是一个整数输入,因此它是预期的并且它可以工作,您可以检查我提供的解决方案。
int main(){
vector<string> v;
int count = 0;
bool value = true;
string s;
char ch;
cout<<"Start entering the name of the students :- "<<endl;
while(value){
getline(cin,s);
v.push_back(s);
count++;
cout<<"Do you want to Enter one more name :- Press 'y/Y' to continue or 'n/N' to end -> ";
cin>>ch;
cin.ignore();
if(ch == 'n'|| ch == 'N') {
value = false;
}
}
cout<<"So, there are total "<<count<<" number of students and their names are :-"<<endl;
for(auto x:v) cout<<x<<endl;
return 0;
}
推荐阅读
- amazon-web-services - 从 AWS 服务访问放置在 VPN 后面的 Rest Endpoint
- javascript - 视频标签未在 Safari 中加载
- r - 需要解决的范围问题
- c# - C#。在达到 5 次失败尝试后,消息“您已用完猜测!它是数字”+ 数字永远不会显示,我需要帮助。谢谢
- azure-devops - Azure 管道自托管代理 - 是否应该有单独的用户来构建和部署?
- mysql - SQL:只要有 5 的倍数就增加一个新列,否则不要
- c# - PowerPDF API - 将 VB 代码转换为 C# - 错误 HRESULT E_FAIL
- python - 在python中将数据提取到矩阵或numpy数组中的有效方法
- scala - 如何解决不同版本的传递依赖?
- c++ - 在程序中找到最小的变量?