I am trying to input data from a text file in C++.
The text file is in that format:
4 15
3 516
25 52 etc.
Each line contains two integers. I don’t know the number of lines in the file so I can bind enough memory and this is what I have come into as a way to solve that:
ifstream filein;
filein.open("text.txt",ios::in);
int count=0;
while (!filein.eof())
{
count++;
filein>>temporary;
}
count=count/2; // This is the number of lines in the text file.
My problem is that I can’t figure out a way to reset
filein
into the initial state (to the beggining of the file so I can actually input the data) other than closing the input stream and opening it again. Is there any other way to do that?
Rather than answer the question you asked, I’m going to answer the question you didn’t ask, namely:
A: Use a
std::vector<>.If you want to read in all of the numbers, regardless of pairing:
If you want to read in all of the numbers, putting alternating numbers into different data structures:
If you want to read in all of the numbers, storing them in some sort of data structure:
Finally, if you want to read the file a line at a time, keeping the first two numbers from each line, discarding the remainder of each line, and storing them a user-defined data structure:
Aside: never use
eof()orgood()in a loop conditional. Doing so almost always produces buggy code, as it would have in your case. Instead prefer invoking the input function in the condition, as I have done above.