【问题标题】:Unable to successfully compare strings无法成功比较字符串
【发布时间】:2015-04-21 16:30:23
【问题描述】:

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

【问题讨论】:

标签: c++ string file io compare


【解决方案1】:

你忘记倒回文件了。

添加以下行

infile.clear();  // Clear the EOF flag
infile.seekg(0); // rewind

紧接着

cin >> word;

另外,您在该行中使用 &lt;&lt; 而不是 &gt;&gt;

infile << word_counter;

由于您没有从文件中读取任何内容,因此封闭的 while 块将处于无限循环中。将该行更改为:

infile >> word_counter;

【讨论】:

  • 好的,我这样做了,但现在它在提示我输入一个单词后就停止了,它可以让我输入,但是当我按 Enter 时没有任何反应。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-01-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多