c++ - 无法成功比较字符串

标签 c++ string file io compare

想法是获取一个文件并打印出文件中的字数。然后提示用户输入一个词,程序会计算这个词被迭代了多少次。但是,我无法从文件中挑选出所选单词,无论它仍然返回 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 << " words\n";

    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 block 保持在无限循环中。将该行更改为:

infile >> word_counter;

关于c++ - 无法成功比较字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28621454/

相关文章:

c++ - 互斥条件等待类错误或错误

javascript - 单引号字符串中的双引号 - NodeJs

Java ArrayList拆分每个对象

Python String 到列表处理

c - 删除记录二进制文件c

c++ - TDD、单元测试和架构变更

c++ - MSVC 错误 - 错误 C2373 : 'description' : redefinition; different type modifiers

python - 将长字符串分成 513 个字符 block | Python 3.3

linux - 使用 libsox 播放 mp3 文件

c++ - 如果你不应该在析构函数中抛出异常,你如何处理其中的错误?