Hi,
I would appreciate if someone can advise me on this issue. I am trying to write a program that read a text file. The input of the text file looks like this:
1 2 3 4 5 6 7
15 50 Y
13 70 Y
13 100 N
18 250 Y
17 110 N
16 200 N
16 80 Y
Now the last column should be read as a character. However, when I read in as a char, it always count that I am reading 8 lines (the actual text file is only 7 lines). When I use a string to read in the last column, it results fine in reading only 7 lines.
#include<iostream>
#include<fstream>
#include<string>
usingnamespace std;
int main()
{
constint MAX=1000;
int age[MAX];
double mpm[MAX];
char resp[MAX]; // If I use char, it reads 8 lines
//string resp[MAX]; // If I use this, it reads 7 lines
int size;
double mpmAverage;
ifstream myFile;
myFile.open("survey1.txt");
if(!myFile)
{
cout<<"Unable to open File!\n";
}
else
{
int i=0;
double mpmSum=0;
while(!myFile.eof())
{
myFile>>age[i]>>mpm[i]>>resp[i]; //This is the part for reading the data
mpmSum+=mpm[i];
i++;
}
size=i;
mpmAverage=mpmSum/size;
cout<<"\t\t\t Survey Report\n";
cout<<"A total of "<<size<<" teenagers were surveyed.\n";
cout<<"Average monthly pocket money = $"<<mpmAverage<<endl;
}
myFile.close();
return 0;
}
It seems it is related with the EOF character. I would appreciate if someone can explain me in clear sentences what is happening. And how should I do it if I want to use char as my data type?