Hello, I tried browsing the web and looking at different places, but I can't figure out how to write a function that could read from text file. Basically what I need is to move what I wrote in main(); into its separate function and that function would need to be able to read from file, but I have no idea how to do that.
Also before anyone ask why I'am not using arrays or structures with this, It's because thats the part of the exercise, to give you more context:
Make a program that could find the heaviest object out of the list. Also find how many objects there are that are at least two times or more lighter than the heaviest.
DO NOT use any kind of arrays or data structures.
Write a separate function to find that object.
DO NOT use division to find lighter objects.
Write a separate function for finding lighter objects.
DO NOT use any sentences for work with console. ( Everything must be done by entering data into the file ).
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
|
#include <iostream>
#include <cmath>
#include <fstream>
#include <cstdlib>
using namespace std;
int main()
{
ifstream input ("U2.txt"); //input file (name)
ofstream output ("U2rez.txt");//output file (name)
int n; //Number in the first line of the file represent total amount
input >> n; //of different variables the program will need to read
int maximum;//Program takes the second variable from the file
input >> maximum;//and sets it as the "heaviest" object
int var1;//int for the next variable
for (int i=0; i<n; i++){ //for cycle set to repeat itself n-times
input >> var1; //with each cycle we take the next variable from file
if (var1>maximum){//and compare it with the maximum one to see if its "heavier"
maximum=var1;//if it is, "maximum" changes its value and the cycle repeats itself
}
}
input.close();
output.close();
return 0;
}
|