从文件输入和输出
Input and output from file
我是编码新手。我得到了这个我几乎完成的任务,但坚持在最后一步。我的老师给了我们正整数文件。任务是查找每行的总计和一行的输出总计以及文件中所有数字的总计。我得到的行总数工作正常,但是当我尝试对所有数字进行总计时,我得到了错误的答案。
请查看我的代码并告诉我我做错了什么。
代码如下:
#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++ 中的输入和输出?
- 创建一个函数以在输入为负数或零时输出字符串.第一次执行用户定义的函数
- 输入到文件并输出到另一个文件,并将流文件传递给函数
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 更改.cpp程序的输入文件中数据的位置会意外更改输出
- C++,在int数组中输入字符串或字符会输出0,而不是ascii或error
- C++多个输入和输出
- 制定带有输入和输出C++的时间表
- 字符的输入/输出操作
- 如何读取单个字符并在输入两个字符序列时输出? 使用 while 循环和C++
- 遇到此问题时遇到困难:允许用户输入数组的值并使用 for,而循环也输出输入的最大数字
- 在数组中输入 n 个整数的列表,并以类似于钟摆来回移动的方式排列它们. 输入-1 3 2 5 4,输出5 3 1 2 4
- C++ 中的矢量重复输出输入
- 类中的重载函数(Students())是输出输入的信息,但它不起作用
- 函数以相反的顺序输出输入问题,并改进算法以解释相等的数字
- 在输出输入文本时对齐输入的文本
- 将多个文件输出/输入到桌面
- 输出输入c++的最短方式
- 将Crypto++中自动种子PNRG的输出输入一个字符串
- 输出输入的拼接版本