无法成功比较字符串
Unable to successfully compare strings
这个想法是取一个文件并打印出文件中的单词数量。然后提示用户输入一个单词,程序会计算该单词的迭代次数。然而,我在从文件中挑选所选单词时遇到了问题,无论它仍然返回0。
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main(){
fstream infile;
int i = 0;
string word_counter;
string file_name;
bool opened = false;
while (opened == false){
cout << "Enter the name of the file to read: ";
cin >> file_name;
infile.open(file_name, fstream::in);
opened = true;
if (!infile.is_open()) {
cout << "ERROR: CANNOT OPEN INPUT FILE" << endl;
cout << endl;
opened = false;
}
}
while (!infile.eof()){
infile >> word_counter;
cout << word_counter << endl;
i++;
}
cout << "Read in " << i << " wordsn";
bool done = false;
while (!done){
string word;
string quit;
int x = 0;
cout << "Enter a word to count how many times it occurs: ";
cin >> word;
while (!infile.eof()){
infile << word_counter;
if (word_counter == word){
x++;
}
}
cout << "The word "" << word << "" occurs " << x << " times" << endl;
cout << "Press any key to continue, or press Q to quit: ";
cin >> quit;
if (quit == "q" || quit == "Q"){
done = true;
}
}
infile.close();
return 0;
}
您忘记倒带文件。
添加以下行
infile.clear(); // Clear the EOF flag
infile.seekg(0); // rewind
之后
cin >> word;
此外,在行中使用<<
而不是>>
infile << word_counter;
由于您没有从文件中读取任何内容,因此封闭的while
块保持在一个无限循环中。将该行更改为:
infile >> word_counter;
相关文章:
- 为什么字符串比较的 == 运算符相对于任一字符串长度线性时间(似乎)?
- 字符串比较中的意外输出
- 如何执行不区分大小写的字符串比较?
- 使用 getline(cin, var) 两次在进行字符串比较时会产生错误 (==)
- <<运算符优先级与字符串比较
- ">"运算符和"<"运算符如何进行字符串比较?
- Qt C++11 字符串通过子字符串比较列出交集
- std::out_of_range字符串比较中的异常
- 我正在尝试从输入文件中读取,然后使用它们的子字符串比较字符串的特定部分
- 字符* 与uint8_t的字符串比较
- 用字符串 c++ 比较对向量的元素
- 使用循环进行词典字符串比较
- 如何为C++映射创建自己的字符串比较对象
- 不带比较()的字符串比较
- 与 IF 语句C++的字符串比较?
- 字符串比较在与变量一起使用时给出不同的输出
- 更快的字符串比较排序,用于唯一()
- C 字符串比较“祝您好运”&gt;“再见”
- C 奇怪的行为和字符串比较
- 子字符串与 std::memcmp 或字符串::比较的比较