将字符串转换为以逗号分隔的双精度变量 (0,07)

Convert string to double variable which is seperated by a comma(0,07)

在 C++ 中,我有一个要读取的双变量,它由逗号 (0,07) 分隔。我首先从 excel 中读取一个字符串并尝试将其转换为双.

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;

它们都return 0 作为输出而不是 0.07。谁能解释一下如何将 double 转换为 0.07 而不是 0。

您可以使用:

std::replace(str.begin(), str.end(), ',', '.'); // #include <algorithm>

在转换之前用点替换逗号。

工作示例:

#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;
}

这样可以吗?

#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 是一个 c++11 函数,但如果要保持双精度,则需要使用它而不是 stof。否则 number 应该是 float

问题是默认语言环境是 "C"(对于 "Classic"),它使用“.”作为小数分隔符,而 excel 使用 OS 之一。那很可能是一种俗语。

您可以:

  • 要求数据的创建者使用类似英语的语言环境导出
  • 在您的程序中设置基于 std::locale("") 的语言环境(以便您的程序使用系统语言环境 - 承认它们是相同的,请参阅 http://en.cppreference.com/w/cpp/locale/locale
  • 设置您使用基于拉丁语的语言环境(例如 IT 或 ES)进行编程
  • 忽略语言环境并将字符串中的“,”替换为“.”-s,然后再尝试将其解释为数字。 (参见 std::replace

您可以为其定义一个自定义的数字方面(numpunct):

class My_punct : public std::numpunct<char> {
protected:
    char do_decimal_point() const {return ',';}//comma
};

然后使用 stringstream and locale:

stringstream ss("0,07");
locale loc(locale(), new My_punct);
ss.imbue(loc);
double d;
ss >> d;

DEMO