c++ - 这段代码有什么问题?它在第二个 cin 可以执行之前终止
问题描述
#include<iostream>
#include<vector>
#include<ios>
#include<limits>
int main()
{
using namespace std;
vector<string> disliked,words;
int n;
cout<<"Enter the word that you dislike."<<endl;
for(string word;cin>>word;)
disliked.push_back(word);
cout<<"Enter the list of words."<<endl;
cin.sync();
for(string word;cin>>word;)
words.push_back(word);
for(int i=0;i<words.size();i++)
{
int n=0;
for(int j=0;j<disliked.size();j++)
{
if(disliked[j]==words[i])
n++;
}
if(n==0)
cout<<words[i]<<endl;
}
cout<<"Program completed."<<endl;
return 0;
}
编写一个程序,把你不喜欢的单词发出哔哔声。首先输入你不喜欢的单词列表。打印“输入单词列表”后程序终止。
解决方案
代替 cin.sync() 使用 cin.clear();
您可能还需要使用 cin.ignore() 。
问题是你有一个 ^D 卡在 cin 中,它阻止了任何未来的 cin 条目。控制 D 关闭系统管道。程序立即退出。
如果您检查结束输入列表的输入,它可能更有用。
使用 cin.sync() 执行:
$ ./a.out
Enter the word that you dislike.
test
a
b
c
^d
Enter the list of words.
Program completed.
$
将 cin.sync() 替换为添加 cin.clear() 和 cin.ignore() 后执行:
$ ./a.out
Enter the word that you dislike.
test
a
b
c
^d
Enter the list of words.
a
b
c
^d
Program completed.
$
推荐阅读
- javascript - 使用 mocha 在 nodejs 中测试 promise 请求
- javascript - 背景图像对于移动设备来说太大了..我该如何解决?
- java - 通过 html 文件运行 JavaFX 应用程序时出现 ClassNotFoundException
- python - 将向量分配给空的熊猫数据框
- c++ - 使用智能指针要求我的类可以公开实例化是否是必要的权衡?
- java - 从一个容器向另一个容器发出 HTTP 请求
- keras - 多属性情感分析
- ios - 以纳秒为单位的快速日期差异不起作用
- javascript - Vue.js在初始化后显示空白页面
- javascript - 如何在 react-spring 中使用 useTransition 对列表的过滤进行动画处理