I am new to C++ so I am trying to understand why the program behaves differently if you do this
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
ifstream fin;
ofstream fout;
fin.open("getfromthisfile.txt");
if(fin.fail())
{
cout << "Input file opening failed.\n";
exit(1);
}
fout.open("sendtothisfile.txt");
if(fin.fail())
{
cout << "Input file opening failed.\n";
exit(1);
}
int next;
int smallest;
int largest;
fin >> next;
smallest=largest=next;
while (! fin.eof())
{
fin >> next;
if(next<smallest)
{
smallest=next;
}
else if( largest < next)
{
largest=next;
}
}
fout << "The largest number in getfromthisfile.txt is " << largest << endl;
fout << "The smallest number in getfromthisfile.txt is " << smallest << endl;
cout << "The largest number in getfromthisfile.txt is " << largest << endl;
cout << "The smallest number in getfromthisfile.txt is " << smallest << endl;
fin.close();
fout.close();
system("pause");
return 0;
}
instead of this...
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
int main()
{
ifstream fin;
ofstream fout;
fin.open("getfromthisfile.txt");
if(fin.fail())
{
cout << "Input file opening failed.\n";
exit(1);
}
fout.open("sendtothisfile.txt");
if(fin.fail())
{
cout << "Input file opening failed.\n";
exit(1);
}
int next;
int smallest;
int largest;
fin >> next;
smallest=largest=next;
while (! fin.eof())
{
fin >> next;
if(next<smallest)
{
smallest=next;
}
else if( largest < next)
{
largest=next;
}
fin >> next;
}
fout << "The largest number in getfromthisfile.txt is " << largest << endl;
fout << "The smallest number in getfromthisfile.txt is " << smallest << endl;
cout << "The largest number in getfromthisfile.txt is " << largest << endl;
cout << "The smallest number in getfromthisfile.txt is " << smallest << endl;
fin.close();
fout.close();
system("pause");
return 0;
}
When I do the first set of code, the program outputs the greatest value is 10 and the smallest value is -10.
When I do the second set of code, the program outputs the greatest value is 9 and the smallest value is -9.
Why does it do this?
Oh here is the data of the input file...
0 1 2 3 4 5 6 7 8 9 10
-1 0 1 2 3 4 5 6 7 8 9
-2 -1 0 1 2 3 4 5 6 7 8
-3 -2 -1 0 1 2 3 4 5 6 7
-4 -3 -2 -1 0 1 2 3 4 5 6
-5 -4 -3 -2 -1 0 1 2 3 4 5
-6 -5 -4 -3 -2 -1 0 1 2 3 4
-7 -6 -5 -4 -3 -2 -1 0 1 2 3
-8 -7 -6 -5 -4 -3 -2 -1 0 1 2
-9 -8 -7 -6 -5 -4 -3 -2 -1 0 1
-10 -9 -8 -7 -6 -5 -4 -3 -2 -1 0
and here is the data of the output file with the first set of code...
The largest number in getfromthisfile.txt is 10
The smallest number in getfromthisfile.txt is -10
and here is the data of the output file with the second set of code...
The largest number in getfromthisfile.txt is 9
The smallest number in getfromthisfile.txt is -9
I would appreciate a good explanation :)