Don't parse the string like that. Just read the values in your desired locale, for example most non-English European locales like de_DE.utf8
, ru_RU.utf8
, or it_IT.UTF-8
... You can even set different locales for different streams, so for example below I'm using the default system locale for std::cin
and a custom locale which uses :
as the radix point in std::cout
#include <iostream>
#include <sstream>
#include <locale>
#include <clocale>
#include <stdlib.h>
template <class charT, charT sep>
class punct_facet: public std::numpunct<charT> {
protected:
charT do_decimal_point() const { return sep; }
};
int main(int argc, char** argv) {
// Use default locale for most std streams
std::locale::global(std::locale(""));
// Use C locale with custom radix point for stdout
std::cout.imbue(std::locale(std::locale("C"), new punct_facet<char, ':'>));
std::stringstream str(argv[1]);
double d;
while (str >> d)
{
std::cout << d << '\n';
}
return 0;
}
In C++ std::locale("")
gives you the current system locale which is probably el_GR.UTF-8
in your case. You can also specify a specific locale to use such as std::locale("fr_FR.utf8")
. Then use std::locale::global
to set the obtained locale globally. Each specific stream can further be imbue
d to a different locale if necessary. You can also use setlocale
for setting some locale preferences
Sample output:
$ g++ read_locale.cpp -o read_locale
$ LC_ALL=el_GR.UTF-8 ./read_locale "2,134 43,54 22,334"
2:134
43:54
22:334
$ LC_ALL=en_US.utf8 ./read_locale "2.134 43.54 22,334"
2:134
43:54
22334
Notice the difference in the last output? That's because ,
is the thousand separator in the English locale
In the example above I'm setting the current locale via LC_ALL
, but on Windows you can't change that easily from the console so just do that in your code. And I'm printing the output directly but pushing it into an array is trivial
Note that those online platforms don't have a non-US locale so I have to use the custom locale. On Linux you can check the available locales with locale -a
In case you really want to get the floating-point numbers as strings (why?) then just read normally. No need for such complex parsing. std::cin
and any kinds of istream
will just stop at blank spaces as expected
#include <iostream>
#include <sstream>
#include <string>
int main(int argc, char** argv) {
std::stringstream str(argv[1]);
std::string s;
while (str >> s)
{
std::cout << s << '\n';
}
return 0;
}
Sample output:
$ g++ read_numbers_as_string.cpp -o read_numbers_as_string
$ ./read_numbers_as_string "2,134 43,54 22,334"
2,134
43,54
22,334
Demo