gpt4 book ai didi

c++ - 使用 : while (cin >> x) and eof

转载 作者:太空宇宙 更新时间:2023-11-03 10:30:46 27 4
gpt4 key购买 nike

我不太确定我认为的工作原理是我的根本问题。我读过一些关于 while(cin>>x) 的帖子,但似乎没有什么能真正回答我的问题。我正在使用这个循环来读取一些文本数据:

while (cin >> x){
searchText.push_back(x);
}

但随后在代码中,我尝试使用以下方法读取单个单词:

cout << "Please enter your target word: ";
string targetWord;
cin >> targetWord;

但是上面的 while 循环/eof 似乎破坏了第二个代码片段(如果我将第二个代码片段向上移动,一切正常,但显然这不是我想要做的)

编辑为清楚起见,这里是完整的代码:

int main()
{
// ask for the target word
// cout << "Please enter your target word: ";
// string targetWord;
// cin >> targetWord;

// ask for and read the search text
cout << "Enter the complete search text, "
"followed by end-of-file: ";
vector<string> searchText;
string x;
while (cin >> x){
searchText.push_back(x);
}

// check that some text was entered
typedef vector<string>::size_type vec_sz;
vec_sz size = searchText.size();
if (size == 0){
cout << endl << "You must enter some text. "
"Please try again." << endl;
return 1;
}

// ask for the target word
cin.clear();
cout << "";
cout << "Please enter your target word: ";
string targetWord;
cin >> targetWord;


int count = 0;
for (int i=0; i<size; ++i){
if (targetWord == searchText[i]){
count++;
}
}

cout << "The target word [" << targetWord << "] was "
"in the search text " << count << " times." << endl;

return 0;
}

我只是想从用户那里获取一些文本……然后是一个搜索词,看看这个词在输入的文本中出现了多少次(非常简单!)

我知道我可以用不同的方式来做,但这里的问题更多是关于如何在之前有 EOF 之后再次使用 cout/cin 流

最佳答案

cin(或任何其他 std::stream)到达文件末尾时,它会设置一个状态来指示这已经发生。

要重置此状态,您需要调用 cin.clear();,这将清除任何“不良”状态,并确保流“正常”以再次使用。如果您正在读取文件并希望从头开始,这也适用。

编辑:我只是拿了上面发布的代码,然后在我的机器上运行它,在顶部添加

#include <iostream>
#include <vector>

using namespace std;

编译运行如下:

$ g++ -Wall words.cpp 
words.cpp: In function ‘int main()’:
words.cpp:40:20: warning: comparison between signed and unsigned integer expressions [-Wsign-compare]
$ ./a.out
Enter the complete search text, followed by end-of-file: aa bb cc [CTRL-D]
Please enter your target word: aa
The target word [aa] was in the search text 1 times.

这是我希望看到的...

Edit2:为了完整性:使用 cin.clear() 的“成功率”将取决于实现。一个更可靠的解决方案是在程序的第一阶段使用不同的方式来标记单词流的结束。可以使用单个 "." 或 "!"或其他不应该出现在“单词”中的东西 - 或更长的东西,例如 "&&@&&",但这使得在 15 页时难以键入和记住进入输入。

关于c++ - 使用 : while (cin >> x) and eof,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17404192/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com