C ++整数奇数/偶数计数器问题

时间:2018-02-03 03:22:57

标签: c++ integer counter

所以我正在编写一个文件,该文件从.dat文件中收集整数列表 计算有多少赔率和赔率。

我为此编写的代码大部分都适用。但有一个模糊的情况是它失败了。如果.dat文件中的一行以偶数结束,那么它将比它应该的数量多1个偶数和1个奇数。

有关最新情况的任何想法? 我试过了什么:

cout << "What is the name of the input file? ";
cin >> fileName;

infile.open(fileName);
if (infile.fail())
{
    cout << "Error opening " << fileName << endl;
}
else 
{
    infile >> number;
    while (!infile.eof())
    {
        count1++;
        infile >> number;

        if (number % 2 != 0)
        {
            odd++;
        }
        else
        {
            even++;
        }
    }
}

infile.close();


cout << "The number of integers is: " << count1 << endl;
cout << "There are " << odd << " odd integers and " << even << " even integers" << endl;

system("pause");
return 0;
}

1 个答案:

答案 0 :(得分:2)

问题在于使用

refreshControl.endRefreshing()
self.yourTableView.contentOffset = CGPoint.zero

决定何时终止循环。请参阅Why is iostream::eof inside a loop condition considered wrong?

使用以下内容:

while (!infile.eof())