我在从.txt文件中添加数字时遇到了一些问题。 [英] I have got some problems with adding up numbers from a .txt file.
问题描述
伙计们!
$
我在学校做了功课,但我已经完成了,但结果并不完全是我想要的。
任务是通过以下规则从文本文件中获取总和:
- 第一列包含数字
- 第二个是0/1布尔值(分隔符是空格)
- 每当布尔值为如果是连续的行,程序应该加上数字
.txt文件如下所示:
20 1
30 1 $
$
40 0 zh
50 1
60 1
我写了以下代码:
Hi, guys!
I got a homework in school and I have done it but the result is not exactly what I wanted.
The task is to get sums from a text file with the following rules:
- the first column contains numbers
- the second is a 0/1 boolean (the separating character is space)
- whenever the boolean is true in continuous lines, the programme should add up the numbers
The .txt file looks like this:
20 1
30 1
40 0
50 1
60 1
And I wrote the following code:
#include <iostream>
#include <fstream>
#include <string>
using namespace std;
int main()
{
string line;
double number;
double sum;
sum = 0;
ifstream homework;
homework.open("homework.txt");
while (!homework.eof())
{
homework >> number >> boolean;
if (boolean == 1)
{
sum += number;
}
}
cout << sum << endl;
homework.close();
system("pause");
return 0;
}
我希望它能写出50和110(因为有一条带有假布尔的行)但相反,它给了我160(所以它总结了所有行with true boolean)。
任何想法?
I wanted it to write out 50 and 110 (because there is a line with a false boolean) but instead, it gave me 160 (so it summed up all lines with true boolean).
Any ideas?
推荐答案
" boolean"是错的。使用可以存储的变量:
"boolean" is wrong. Use a variable where it can be stored:
int iboolean;
while (!homework.eof())
{
homework >> number >> iboolean;
if (iboolean == 1)
{
sum += number;
}
}
问候,Guido
这篇关于我在从.txt文件中添加数字时遇到了一些问题。的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!