首页 > 解决方案 > 这段代码有什么问题?它在第二个 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;
}

编写一个程序,把你不喜欢的单词发出哔哔声。首先输入你不喜欢的单词列表。打印“输入单词列表”后程序终止。

标签: c++debugging

解决方案


代替 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.
$

推荐阅读