c++ - 从文件输入和输出

标签 c++ file input output

我是编码新手。我得到了这个我几乎完成但停留在最后一步的任务。我的老师给了我们正整数文件。一个任务是找到每一行的总数并输出一行的总数以及文件中所有数字的总数。我得到的行总计工作正常,但是当我尝试计算所有数字的总和时,我得到了错误的答案。

请检查我的代码并告诉我我做错了什么。

代码如下:

#include <iostream>
#include <string>
#include <fstream>
#include<iomanip>
using namespace std;

int main()
{
ifstream infile; ofstream outfile;
int counter, counter2, line, sum, num;
double total;
infile.open("E:\\Lab assignments\\numberfile.txt");
if (!infile)
{
cout << "File not found, closing program" << endl;
system("pause");
exit(1);
}
outfile.open("E:\\Lab assignments\\outfile.txt");
if (!outfile)
{
cout << "Output file could not be created, closing program" << endl;
system("pause");
exit(1);
}


while (!infile.eof())

for (counter = 1; counter <= 8; counter++)
{
sum = 0;
if (counter != 9)
{
for (line = 1; line < 8; line++)
{
infile >> num;
outfile << right;
outfile << setw(6);
outfile << num << " ";
sum = sum + num;

outfile << " ";


}
outfile << "Total per line = " << sum;
outfile << endl;



}




}
total = 0;
for (counter2 = 0; counter2 <= 8; counter2++)
{

{
infile >> sum;
total = total + sum;
}

}
outfile << "All numbers total= " << total;

infile.close();
outfile.close();
return 0;


}

和带有数字的文件:

346 130 982 90 656 117 595
415 948 126 4 558 571 87
42 360 412 721 463 47 119
441 190 985 214 509 2 571
77 81 681 651 995 93 74 
310 9 995 561 92 14 288
466 664 892 8 766 34 639
151 64 98 813 67 834 369

最佳答案

在同一循环中计算总和和每一行的总和将显着简化您的任务,并将消除代码中隐藏的问题。简单点:)

关于c++ - 从文件输入和输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50149365/

相关文章:

c++ - Direct X 11 锯齿状边缘

c - 为什么 fputc 不更新此代码段中的字符?

css - CSS 文件排序重要吗?如果重要,为什么?

windows - 使用 Windows 批处理脚本将文本文件拆分为多个文件

Java在while循环中读取系统输入

c - 使用 netbeans 从 c 中的命令行进行标准输入

c++ - 使用线程对数组的两半进行排序,但仅对后半部分进行排序

c++ - 模板化类,如何表示为另一个类的成员变量而不使此类模板化

c++ - `auto *x = new some_struct{};`如何是未初始化的变量?

javascript - 使用 Javascript 根据下拉菜单选择填充输入字段