-
One Extra Input
Hello,
I am pulling in lines from a file. I am however getting one copy of the last record at the end...any suggestions
Code:
fstream infile("hw5.data",ios::in);
info main_struct;
string line_string;
string fips;
string d_name;
string r_code;
int d_pop;
int sd_enrol;
int st_need;
while(infile)
{
getline(infile,line_string,'\n');
parse_string(line_string,fips,d_name,r_code,d_pop,sd_enrol,st_need);
fips = "";
d_name = "";
r_code = "";
d_pop;
sd_enrol;
st_need;
cout << endl << endl << endl;
}
-
Change this:
Code:
while(infile)
{
getline(infile,line_string,'\n');
To this:
Code:
while(getline(infile,line_string,'\n'))
{
The eofbit for infile is only set after you fail to read input, so the loop will iterate once more than you want and line_string will have the same value as the last iteration, so it looks like you're reading the last line twice.
-
The method Prelude just showed you is called a Priming Read.
-
Thank You this fixed it!!!!!!!!!
-
Code:
fstream infile("hw5.data",ios::in);
info main_struct;
string line_string;
string fips;
string d_name;
string r_code;
int d_pop;
int sd_enrol;
int st_need;
getline(infile,line_string,'\n'); //read one before loop
while(infile)
{
parse_string(line_string,fips,d_name,r_code,d_pop, sd_enrol,st_need);
fips = "";
d_name = "";
r_code = "";
d_pop;
sd_enrol;
st_need;
cout << endl << endl << endl;
getline(infile,line_string,'\n');
}
I was taught to always read something before your loop, so this should also stop from reading and extra record
-
Yes, this is another example of a priming read. It gets the same results as prelude's code, it just does is a bit more code.
-
>> I was taught to always read something before your loop, so this should also stop from reading and extra record
One disadvantage of this type of code is that you cannot use continue to skip the rest of the code block. For example, if you want to skip blank lines, you might check line_string.empty(), and continue if it is true. With the read at the end of the code block you will skip the read.