I have file with some data. I would like to decide what type of data there are: if everythng there is a number I want to push that to vector. But if there is even one data that is now a string I would like to push all of it to vector. I wrote something like this:
ifstream dataFile;
dataFile.open(fileName);
if(!dataFile.good()){
cout<<"File with data cannot be open"<<endl;
return 0;
}
cout<<"File open correctly..."<<endl;
bool isString = false;
vector<double> doubleData;
while (!dataFile.eof()){
double f;
dataFile>>f;
if(!dataFile.fail()){
doubleData.push_back(f);
}
else{
cout<<"it's string"<<endl; //(*) always
isString = true;
break;
}
}
if(isString){
dataFile.close(); //(**) reopen a file
dataFile.open(fileName);
vector<string> stringData;
while (!dataFile.eof()){
string s;
dataFile>>s;
if(!dataFile.fail()){
stringData.push_back(s);
}
}
cout<<"String data:"<<endl;
for (int i = 0; i< stringData.size();i++){
cout<<stringData[i]<<endl;
}
//showTime(stringData);
return 0;
}
cout<<"double data:"<<endl;
for (int i = 0; i< doubleData.size();i++){
cout<<doubleData[i]<<endl;
}
//showTime(doubleData);
return 0;
My code always reach line (*) at the end and therefore presume it's string data. I think it's when it reaches eof(). Am I right? How to fix it?
And one more: I need to re-open my file (*line (**)*) to read data into stringData
properly. I can guess it is because I am at the end of file after previous while loop. Am I right? Is there any other, more elegant way to do this? Moving cursor in file to the beginning? I know there is something like fseek ( dataFile , 0 , SEEK_SET );
but I receive compiler error as my dataFile is ifstream
instead of File*
. Any suggestions?