计算int出现在文件中的次数

时间:2013-04-19 14:27:57

标签: c++ file file-io counter

我正在创建一个简单的程序,用于读取文件和用户的值,然后计算该值在文件中出现的时间。到目前为止我已经做到了这一点,编译得很好,但是当你输入一个数字时,那里什么也没发生。我很难过。很抱歉,如果这是非常基本的,但我无法理解。

这是我到目前为止所做的。

#include <stdlib.h>
#include <iostream>
#include <fstream>

using namespace std;

int hold,searchnumber, counter=0;

int main()
{ 

cout << "This program reads the contents of a file to discover if a number you enter exists in it, and how many times. \n";
cout << "What number would you like to search for? \n";
cout << "Number : ";
cin  >> searchnumber;

ifstream infile("problem2.txt");
if(!infile)
{
    cout << "Can't open file problem2.txt";
    exit(EXIT_FAILURE);
}
int sum=0,number;
infile >> number;
while (!infile.eof())
{
    if (number == searchnumber); 
    counter = counter += 1;
}
{
    cout << "The number " <<searchnumber << " appears in the file " << counter <<" times! \n";
    cin >> hold;
}

infile.close();
}

4 个答案:

答案 0 :(得分:4)

本节包含两个问题:

infile >> number;
while (!infile.eof())
{
    if (number == searchnumber); 
    counter = counter += 1;
}

while条件是真还是假,如果是真的,它会永远保持不变,这可能就是“没有发生”的原因。循环中没有任何东西可以改变infile的状态。

将前两行合并为:

while (infile >> number)

然后你至少要浏览一下这个文件。

现在,这个:

    if (number == searchnumber); 
    counter = counter += 1;

由于if语句后面有分号,你基本上是在说“如果它是正确的号码,什么都不做”,然后更新计数器,无论你是否找到了号码。删除分号。

像往常一样,写得太多太慢。

答案 1 :(得分:1)

你在这一行有一个无限循环:

while (!infile.eof())
{
    if (number == searchnumber); 
    counter = counter += 1;
}

你打开文件并读入它上面的行,但是这个循环只会继续,直到你点击eof,但由于你没有读过任何其他东西,只要你进入循环它不是eof它永远不会退出。

答案 2 :(得分:0)

infile >> number;
while (!infile.eof())
{
  if (number == searchnumber); 
     counter = counter += 1;  
}

应该是

while (infile >> number)
{
   if (number == searchnumber)
     counter += 1;
}

每次比较之前,您需要从文件中读取一个数字。不要简单地在循环中读取文件。

BTW:您似乎没有使用sum变量,请将其删除。

答案 3 :(得分:0)

1

if (number == searchnumber); 
    counter = counter += 1;

应该是

if (number == searchnumber) 
    counter = counter += 1;

2。 sum未使用。

相关问题