I have a txt file called 'sample.txt' with data of the form
1.0
2.1
abc
4.2
I would like to extract the numbers 1.0, 2.1, 4.2 from the txt file and ignore the string 'abc'.
Before I extract the data, I would like to first count exactly how many numbers are there in the txt file.
Because I want to extract the numbers into a dynamic array and I need to know what size of array to create first.
My code for counting the number of numbers in the txt file is
ifstream myfile;
myfile.open ("sample.txt");
int dataCount = 0; // to count number of numbers
while (!myfile.eof())
{
double x;
myfile >> x;
if (myfile.fail()) // no extraction took place
{
myfile.clear();
myfile.ignore(numeric_limits<streamsize>::max(), '\n');
continue; // do nothing and start reading next data
}
// Count up if x successfully extracted
dataCount++;
}
So now I am done counting the number of numbers but there is also nothing left in the ifstream myfile for me to extract. Is there anyway to count the numbers without extracting anything away from the ifstream myfile?
This is for a school assignment where I am not permitted to use a vector.
You can just close the file and open it up again. Or you could clear the end of file flag and seek back to the beginning.
myfile.clear();
myfile.seekg(0); // rewind the file to the beginning