0

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?

Malvinka
  • 778
  • 1
  • 7
  • 25
  • 1
    Read e.g. [Why is iostream::eof inside a loop condition considered wrong](http://stackoverflow.com/q/5605125/440558). – Some programmer dude Jun 03 '15 at 12:02
  • Are you looking for a binary file full of `double`, or a text file full of numerals? – Beta Jun 03 '15 at 12:04
  • I need both. Each file I receive(no matterwhat's in it) I need to decide if I can treat is as a double or do I have to use string (if te format does not suits double) – Malvinka Jun 03 '15 at 12:11
  • @Joachim Pileborg That works. Thanks a lot. – Malvinka Jun 03 '15 at 12:27
  • 1
    About the "one more": try with `dataFile.clear(); dataFile.seekg(0);` (the "clear()" is to reset the possible EOF bit of the stream). – Alberto M Jun 03 '15 at 12:41

0 Answers0