这段代码出了什么问题?它在第二个 cin 可以执行之前终止
What's wrong in this code?It terminates just before second cin can execute
#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()。
问题是您在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.clear()和cin.ignore()替换cin.sync()后执行。
$ ./a.out
Enter the word that you dislike.
test
a
b
c
^d
Enter the list of words.
a
b
c
^d
Program completed.
$
相关文章:
- 我有两个类需要在同一 cpp 文件中相互引用,但第一个类无法识别第二个类类型的对象
- 等待整个 omp 块完成,然后再调用第二个函数
- 我想在C++中读取一些多个字符,但它永远不会读取第二个字符
- 如何在创建自定义迭代器时获得 std::p air 的第一个和第二个?
- WinAPI 在单击第一个对话框上的按钮控件并销毁第一个对话框后创建第二个对话框
- 将第二个 GATT 服务添加到 Movesense 容器
- 如何在 c++ 中根据第二个元素按降序对列表进行排序
- 对的排序向量 (std::vector<pair<int, int>>) 按对的第一个元素搜索并更新第二个元素值
- 比较 2 个向量并从第二个向量中删除在第一个 - c++ 中找不到的元素
- 为什么这个程序没有打印返回的迭代器的正确第二个元素?
- 使第二个类的构造函数成为第一个类中的友元函数
- 为什么第二个代码给出了预期的结果,而第一个代码却没有?
- 为什么第一个代码块产生垃圾值,而第二个代码块将类成员的值相加?
- 如何在我的代码中修复无穷循环?我认为它跳过了第二个CIN,因此它一直在循环
- 这段代码出了什么问题?它在第二个 cin 可以执行之前终止
- 当一长串字符传递给第一个 cin 时,为什么不暂停第二个 cin 上的输入?
- 程序跳过第二个 cin
- 我的第一个 cin 被忽略了,它只接受第二个
- 当 cin.getline() 的第二个参数大于数组长度时,不可预测的字符串长度
- (cin >> buf && !buf.empty()) 中的第二个条件是多余的吗?