ifstream fin(filename);
double s;
int count=0;
while(1){
fin>>s;
count=count+1;
if (fin.eof()) {fin.clear( );
break;
}
}
for (int k=0; k<ndata-1;k++){
cout<<k<<endl;
fin>>data[k];
if (fin.eof()){
cout<<"End of file reached exiting"<<endl;
exit(1);
}
}
I want read data from file and put them in data vector. But I want to check the vector size.I can not "clear" the bit eof so that if I check it doesn't fill the vector and jump do cout<<"End of file..."
(1) Your indentation is messed up because you're mixing tabs and spaces.
(2) Using eof is often error prone if you aren't using it in a valid place. You should instead be checking the success of the extraction of a number instead.
(3) If the file stream is at its end, calling fin.clear() only resets the failbit. It doesn't reset the file offset.
(4) Why ndata - 1? Possible "off-by-one" fencepost error.
What does your file look like? Why are you looping over your file twice?
<edit: I assume you are iterating it the first time simply to get the count of numbers. But why? If you don't know the size of an array at compile-time, you should be using a vector anyway.>
If your file looks like: 42 3.14 2.78 ... and you know the maximum number of elements, you can do something like:
1 2 3 4 5 6 7 8 9 10 11
constint MaxSize = 1000;
double arr[MaxSize];
int size = 0;
double num;
ifstream fin(filename);
while (fin >> num && size < MaxSize)
{
data[size] = num;
size++;
}
ifstream fin(filename);
double s;
int count = 0;
while (1)
{
fin >> s;
count = count + 1;
if (fin.eof())
{
fin.clear(); // <--- Resets the state bits, but leaves the file pointer at the end.
break;
}
}
for (int k = 0; k < ndata - 1; k++)
{
cout << k << endl;
fin >> data[k];
if (fin.eof()) // <--- Abetter choice "if (!fin)". Checks more than just "oef" bit".
{
cout << "End of file reached exiting" << endl;
exit(1); // <--- If this is in "main" use return not "exit()". Actually never use "exit()".
}
}
"exit()" is a C function. It works, but it does not know about classes or about cleaning up anything before a program ends. "exit()" is an unconditional exit from the program and has the potential for problems. You should favor return except in some rare cases.