我的任务如下: 我收到的文本文件中包含 8行的数字,每行包含 7个数字。我将采用这些数字,读取并将它们转移到一个新文件中。然后从新文件的新行中获取数据,我必须执行以下操作:
在每个 7个数字中找到最高和最低数字。
我的教授教我们基本的文件处理。我只知道如何使用循环,if和else,以及您在此代码中看到的文件处理范围。
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
//MY VARIABLES
float avg;
int number, line, max, min;
int counter = 1;
int sum;
//OPENING FILES
ifstream fromFile;
ofstream toFile;
toFile.open("NumberInFile.txt");
fromFile.open("NumberFile.txt");
while (!fromFile.eof()) // READ EVERY NUMBER FROM THE FILE
{
if (counter <= 7) //LINE #1
{
cout << "Line 1: ";
int sum = 0;
do
{
fromFile >> number;
toFile << number << " ";
cout << number << " ";
line = 1;
counter++;
sum += number;
} while (counter <= 7);
toFile << "\n";
}
else if (counter > 7 && counter <= 14) //LINE #2
{
cout << "\nLine 2: ";
do
{
fromFile >> number;
toFile << number << " ";
cout << number << " ";
line = 2;
counter++;
} while (counter > 7 && counter <= 14);
toFile << "\n";
}
else if (counter > 14 && counter <= 21) //LINE #3
{
cout << "\nLine 3: ";
do
{
fromFile >> number;
toFile << number << " ";
cout << number << " ";
line = 3;
counter++;
} while (counter > 14 && counter <= 21);
toFile << "\n";
}
}
//CLOSES FILES
toFile.close();
fromFile.close();
system("pause");
return 0;
}
答案 0 :(得分:-1)
进行以下更改,如果您不理解任何内容,请自由询问:
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
//MY VARIABLES
int number, max, min, sum;
//OPENING FILES
ifstream fromFile;
ofstream toFile;
toFile.open("SecondFile.txt"); //Don't overwrite the same file
fromFile.open("NumberFile.txt");
//IF FILE DIDN'T OPEN SUCCESSFULLY
if (!fromFile)
{
cout << "There was an error" << endl;
exit(1);
}
//IF FILE OPENED SUCCESSFULLY
else
{
cout << "No error, file opened successfully" << endl;
toFile << "This file contains the calculations for this project" << endl;
}
while (!fromFile.eof()) //WILL LOOP UNTIL IT HAS READ EVERY NUMBER FROM THE FILE
{
for(int i=1; i<=8; i++){ //LOOP for counting rows
cout <<"\nLine "<<i<<": ";
int sum = 0;
max = 0;
min = 0;
int j=1;
do
{
fromFile >> number;
if(max == 0 && min == 0){
max = number;
min = number;
}
if(number > max){
max = number;
}
else if(number < min){
min = number;
}
toFile << number << " ";
cout << number << " ";
j++;
sum += number;
} while (j <= 7);
toFile << "Max: "<<max<<", Min: "<<min<<", Sum: "<<sum<<", Average: "<<sum/7<<endl;
}
}
//CLOSES FILES
toFile.close();
fromFile.close();
return 0;
}
输入文件:
输出文件: