Search code examples
c++iostream

Read float from input stream without trailing "E"


I do the following:

float f;
cin >> f;

On the string:

0.123W

Number 0.123 will be properly read to f, and stream reading will be stopped on 'W'. But if we enter:

0.123E

operation will fail and cin.fail() will return true. Probably the trailing 'E' will be treated as part of scientific notation.

I've tried cin.unsetf(std::ios::scientific); with no success.

Is there any possibility to disable treating character 'E' specially?


Solution

  • Yes, you have to parse it your self. Here is some code:

    // Note: Requires C++11
    #include <string>
    #include <algorithm>
    #include <stdexcept>
    #include <cctype>
    using namespace std;
    
    float string_to_float (const string& str)
    {
        size_t pos;
        float value = stof (str, &pos);
        // Check if whole string is used. Only allow extra chars if isblank()
        if (pos != str.length()) {
            if (not all_of (str.cbegin()+pos, str.cend(), isblank))
                throw invalid_argument ("string_to_float: extra characters");
        }
        return value;
    }
    

    Usage:

    #include <iostream>
    string str;
    if (cin >> str) {
        float val = string_to_float (str);
        cout << "Got " << val << "\n";
    } else cerr << "cin error!\n"; // or eof?