1

我正在尝试编写一个程序,该程序将要求用户输入一个整数,然后继续搜索预定义的文本文件(仅包含整数)以查找该特定整数的出现次数,并打印结果。这是我到目前为止编写的代码(运行时不起作用),但我不知道我是否在这里朝着正确的方向前进,或者我是否应该尝试从文件中读取所有整数成一个数组,甚至完全做其他事情。我应该补充一点,这是家庭作业,我只是在寻找指针,而不是完整的解决方案。我已经尝试了我能想到的一切,但没有取得太大进展。有人能指出我正确的方向吗?提前致谢。

#include <iostream>
#include <iomanip>
#include <fstream>

using namespace std;

int main()
{
    int x, y;
    int sum1 = 0;
    ifstream infile ("file.txt");
    if (infile)
        cout << "File successfully opened" << endl;
    else
    {
        cout << "Can't open file" << endl;
        exit (EXIT_FAILURE);
    }
    cout << "Input number: ";
    cin >> x;
int number;
while(!infile.eof()) //this is where my problems start
         {
           infile >> number;
         }
while(number = x) //doesn't seem to be working, not sure if I should even be using
                  //a while statement
         {
           sum1++;
         }
        cout << sum1++ << " " ;
}
4

2 回答 2

4

You are using single = in comparison statement: while(number = x) which is wrong. use == in comparison

Do it like:

while(number == x)  //note ==
             ^^

Other thing to note is that you are using while 2 times that's logically not good and using !infile.eof() is also not good as you may not get expected results (1 more than original)

Try this code:

int number;

while (true) {

    infile >> number;
    if( infile.eof() )      //This line will help in avoiding processing last value twice 
      break;

    if (number == x)
    {
        sum1++;
        cout << sum1++ << " " ;
    }
}
于 2013-07-25T19:35:18.317 回答
3

Do this:

// ...
int number;
infile >> number;
while(!infile.eof())
{
    if (number == x)
    {
        sum1++;
    }
    infile >> number;
}
cout << sum1;
于 2013-07-25T19:35:39.503 回答