Reputation: 153
In C++ I've got a double variable to be read which is seperated by a comma(0,07).I am first reading it a string from an excel and trying to converting it into a double.
string str = "0,07"; // Actually from Excel.
double number = strtod(str .c_str(), NULL);
double number1 = atof(str .c_str());
cout << number<<endl;
cout <<number1<<endl;
Both of them return 0 as output instead of 0.07. can someone explain me how to convert double to 0.07 instead of 0.
Upvotes: 3
Views: 4053
Reputation: 17999
You can use:
std::replace(str.begin(), str.end(), ',', '.'); // #include <algorithm>
to replace the comma by a dot before converting.
Working example:
#include <iostream>
#include <algorithm>
using namespace std;
int main()
{
string str = "0,07"; // Actually from Excel.
replace(str.begin(), str.end(), ',', '.');
double number = strtod(str.c_str(), NULL);
double number1 = atof(str.c_str());
cout << number << endl;
cout << number1 << endl;
return 0;
}
Upvotes: -1
Reputation: 172934
You can define a customized numeric facet (numpunct) for it:
class My_punct : public std::numpunct<char> {
protected:
char do_decimal_point() const {return ',';}//comma
};
and then use a stringstream and locale with it:
stringstream ss("0,07");
locale loc(locale(), new My_punct);
ss.imbue(loc);
double d;
ss >> d;
Upvotes: 3
Reputation: 20730
The problem is that the default locale is the "C" (for "Classic"), that uses '.' as decimal separator, while excel use the one of the OS. that is most likely the one of a lain language.
You can either:
std::locale("")
(so that your program work with the system locale -admitting they are the same, see http://en.cppreference.com/w/cpp/locale/locale)Upvotes: 2
Reputation: 109
Would this be fine ?
#include <string>
#include <iostream>
using namespace std;
int main()
{
string str = "0,07"; // Actually from Excel.
int index = str.find(',');
str.replace(index, index+1, '.');
double number = stod(str);
cout << number << endl;
return 0;
}
PS: stod
is a c++11
function, but you need to use it instead of stof
if you want to keep the double precision. Otherwise number
should be a float
Upvotes: -1