S
sherifffruitfly
Hi - I'm just learning basic file i/o stuff, and the following input
routine skips the first entry in text files. I would guess it's a
similar phenomenon as when there's a CR left in the buffer and you need
to do a cin.get() to clear it. But I really don't know. Lil help?
Another thing: I initially wanted to use the conditional-? operator
inline in the cout statement at the end. Doing so never worked
(compiles fine, just gives incorrect answers). Why is this?
The test file I used contained only "1 2 3 4 5 6 7 8 9 10" (without
quotes). Runs always left the 1 out of the loop value cout.
TIA!
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
const int SIZE = 60;
const int FILESIZEMAX = 1000;
int main()
{
char filename[SIZE];
ifstream inFile;
cout << "File name: ";
cin.getline(filename,SIZE);
inFile.open(filename);
if (!inFile.is_open())
{
cout << "Couldn't open " << filename << endl;
cout << "Terminating execution\n";
exit(EXIT_FAILURE);
}
double value;
double sum = 0.0;
int count = 0;
double avg = 0.0;
inFile >> value;
while (inFile.good() && count<FILESIZEMAX)
{
++count;
sum += value;
inFile >> value;
cout << value << endl;
}
if (inFile.eof())
{
cout << "End of file reached\n";
}
else if (inFile.fail())
{
cout << "Data mismatch.\n";
}
else
{
cout << "Input terminated for unknown reason.\n";
}
cout << "Items read: " << count << endl;
cout << "Sum: " << sum << endl;
avg = count !=0 ? sum/count: 0.0;
cout << "Average: " << avg << endl;
cout << endl;
inFile.close();
return 0;
routine skips the first entry in text files. I would guess it's a
similar phenomenon as when there's a CR left in the buffer and you need
to do a cin.get() to clear it. But I really don't know. Lil help?
Another thing: I initially wanted to use the conditional-? operator
inline in the cout statement at the end. Doing so never worked
(compiles fine, just gives incorrect answers). Why is this?
The test file I used contained only "1 2 3 4 5 6 7 8 9 10" (without
quotes). Runs always left the 1 out of the loop value cout.
TIA!
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
const int SIZE = 60;
const int FILESIZEMAX = 1000;
int main()
{
char filename[SIZE];
ifstream inFile;
cout << "File name: ";
cin.getline(filename,SIZE);
inFile.open(filename);
if (!inFile.is_open())
{
cout << "Couldn't open " << filename << endl;
cout << "Terminating execution\n";
exit(EXIT_FAILURE);
}
double value;
double sum = 0.0;
int count = 0;
double avg = 0.0;
inFile >> value;
while (inFile.good() && count<FILESIZEMAX)
{
++count;
sum += value;
inFile >> value;
cout << value << endl;
}
if (inFile.eof())
{
cout << "End of file reached\n";
}
else if (inFile.fail())
{
cout << "Data mismatch.\n";
}
else
{
cout << "Input terminated for unknown reason.\n";
}
cout << "Items read: " << count << endl;
cout << "Sum: " << sum << endl;
avg = count !=0 ? sum/count: 0.0;
cout << "Average: " << avg << endl;
cout << endl;
inFile.close();
return 0;