smilu
smilu

Reputation: 899

File not reading properly C++ ifstream

I have an application where I'm using ifstream to read the file. I have 1000 numbers in the file in each line. My application should read all these lines.

But when I have the number of lines less than 800 it is showing the count as 0 why is it like this. The code is below.

int tmp, count=0,ucount=0; 

ifstream fin("rnum.txt");
while(fin >> tmp)
{
    count++;
}
cout<<"showing count: "<<count<<endl;
ucount=count;
fin.open("rnum.txt");
int i=0;
cout<<"Before entering loop"<<count<<endl;
while(fin >> tmp){
    iArray[i++]=tmp;
}

When I read a file with 1000 lines it is only reading 720 lines too. I don't understand why its reading like this.

Is there anything wrong in the code.

My requirement is to take the number of lines COUNT to the ucount variable.

Upvotes: 0

Views: 2817

Answers (4)

WARhead
WARhead

Reputation: 691

If the Input is improper (if a char instead of digit is encountered), the >> operation fails and fin >> tmp return false thereby breaking the loop prematurely.

moreover You should close the file before reopening it. And I beleive the functionality You needed/wanted was merely fin.seekg(0).

Besides your code can be simplified to :

int temp;
ifstream fin("rnum.txt");
vector<int> iArray;
while(fin >> tmp)
{
    iArray.push_back(tmp);
}

std::cout << "showing count : " << iArray.size();

As suggested by @trojanfoe in https://stackoverflow.com/a/16058205/6459731

Upvotes: 0

suspectus
suspectus

Reputation: 17258

To count the number of lines in the file use getline function.

#include<string>

std::string line;
while (std::getline(fin, line))
{
    ++count;
}

Upvotes: 1

parkydr
parkydr

Reputation: 7784

You need to close the file with fin.close() before opening the file for the second time or leave the file open, reset the read pointer and clear the eof flag.

Upvotes: 0

trojanfoe
trojanfoe

Reputation: 122381

This won't solve your error, as I believe that is related to the input file itself, however reading the file once will at least make it quicker:

vector<int> iArray;
int tmp; 

ifstream fin("rnum.txt");
while (fin >> tmp)
{
    iArray.push_back(tmp);
}
cout << "showing count: " << iArray.size() << endl;

Upvotes: 0

Related Questions