【发布时间】:2018-02-03 03:22:57
【问题描述】:
所以我正在编写一个从 .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;
}
【问题讨论】:
-
你跳过第一个数字,(在循环之前)。
-
示例输入在哪里?