robbannn
robbannn

Reputation: 5013

Getting data from ifstream that failed conversion

I'm using an ifstream object to read double's from a text-file.

ifstreamObject >> floatVariable;

In the case that the read is not able to be converted into a double, I wondering how I can get the non-convertable data and make it into a string instead? Is it possible doing it this way without first storing it as a string and then try to convert it?

I want to do it this way so that the object throws an exception. The catch-block is intended to handle the values that are not convertable to double and store them in a separate txt-file for later analysis.

Upvotes: 0

Views: 99

Answers (2)

Galik
Galik

Reputation: 48615

I suppose the important thing is to remember to clear the error that you get when the read fails:

int main()
{
    std::ifstream ifs("test.txt");

    float f;
    if(ifs >> f)
    {
        // deal with float f
        std::cout << "f: " << f << '\n';
    }
    else // failed to read a float
    {
        ifs.clear(); // clear file error

        std::string s;
        if(ifs >> s)
        {
            // now deal with string s
            std::cout << "s: " << s << '\n';
        }
    }
}

I recommend against using try{} catch{} exceptions for this because non-convertable input is one of your expected results. That is not truly exceptional.

Upvotes: 1

atlanteh
atlanteh

Reputation: 5835

Use tellg to find current location and if conversion failed use seekg to go backwards and convert it to string.

Upvotes: 1

Related Questions