【问题标题】:Counting the number of times an int appears in a file计算 int 在文件中出现的次数
【发布时间】:2013-04-19 14:27:56
【问题描述】:

我正在制作一个简单的程序,它读取文件和用户的值,然后计算该值在文件中出现的次数。到目前为止,我已经做到了,它编译得很好,但是当你输入一个数字时,那里什么也没有发生。我难住了。对不起,如果这是非常基本的,但我无法超越。

这是我目前所拥有的。

#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();
}

【问题讨论】:

  • 其他人已经回答了眼前的问题,但这里有一个更高级别的提示:当您尝试编写一个执行两件事的程序时(例如,从用户那里获取一个数字,然后扫描一个文件),在尝试集成它们之前,您应该分别编写和测试这两个函数。这样一来,当出现问题时,您就会(通常)知道该往哪里看。
  • 请记住考虑您的文件是否包含非数字、大数字等。简单形式的更正循环仅适用于包含有效整数的文件。例如它将无法在像这样的文件中找到 2 1 '1 33333333333333333333333333 1'

标签: c++ file file-io counter


【解决方案1】:

本节包含两个问题:

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

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

将前两行合并为:

while (infile >> number)

那么你至少要遍历文件。

现在,这个:

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

由于 if 语句后有一个分号,因此您基本上是在说“如果它是正确的数字,则什么也不做”,然后更新计数器,无论您是否找到该数字。删除分号。

像往常一样,写的太多太慢了。

【讨论】:

  • 非常感谢!我理解你的解释,以及它为什么有效。您的帮助是如此宝贵,其他人的回复也是如此。一旦它允许我就会给你打勾:)
【解决方案2】:

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

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

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

【讨论】:

    【解决方案3】:

    1.

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

    应该是

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

    2。 sum 未使用。

    【讨论】:

    • @Drew Dormann 去掉if (number == searchnumber)之后的分号
    • 啊!我的眯眼有缺陷!
    【解决方案4】:
    infile >> number;
    while (!infile.eof())
    {
      if (number == searchnumber); 
         counter = counter += 1;  
    }
    

    应该是

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

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

    顺便说一句:你的sum 变量似乎没有使用,删除它。

    【讨论】:

      猜你喜欢
      • 2017-02-13
      • 1970-01-01
      • 1970-01-01
      • 2022-01-18
      • 1970-01-01
      • 2013-12-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多