I want in my program read double values from different text files. Some files contain doubles in format 'xx.yyy' (dot is a separator), but some other - 'xx,yyy' (comma is a separator). I use c++ streams for reading.
If you know the format of each file ahead of time, you can imbue()
a std::ifstream
with a custom std::locale
whose std::numpunct
facet specifies the desired thousands_sep
and decimal_point
characters. Then operator>>
will be able to parse the double
values as expected.
See How can I set the decimal separator to be a comma? for how to specify a custom decimal_point
. The same approach applies to thousands_sep
as well.
If you don't know the format ahead of time, you will have to read the double
s as strings first, then manually parse them to determine which format they are using, and then you can imbue()
a std::istringstream
as needed to then convert the strings to double
. If all of the double
s in a given file use the same format, then you could do this for the 1st double
and then imbue()
the std::ifstream
as needed for subsequent double
s.