Search code examples
c++locale

Convert string to double using custom numpunct doesn't work as expected


I am trying to convert a string to a double using a custom numpunct. I want the conversion to fail if the string is not in a currency-style format - e.g. 1,000,000.0

#include <iostream>
#include <sstream>

using namespace std;

class ThousandCommaSeparator: public std::numpunct<char>
{
public:
    ThousandCommaSeparator(){}
protected:
    virtual char do_decimal_point() const { return '.'; }
    virtual char do_thousands_sep() const { return ','; }
    virtual string_type do_grouping() const { return "\3";}
};

int main()
{
    istringstream ss("2015/05/03");
    ss.imbue(locale(cout.getloc(),new ThousandCommaSeparator));

    double output;

    if (ss >> output)
    {
        cout << "Success: " << output << endl;
    }
    else
    {
        cout << "Failure: " << output << endl;
    }
}

I want the above to fail, but it always succeeds, and sets the value of output to 2015. I'm guessing I'm using numpunct incorrectly, hopefully someone can point me in the right direction!


Solution

  • Thousands separators in an input stream are optional. If they are present, they must be placed correctly, but they don't have to be present.

    Thus, 2015 is a valid input to convert to an number regardless of std::numpunct.