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

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

本文关键字:分隔 变量 转换 字符串      更新时间:2023-10-16

在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;

它们都返回0作为输出,而不是0.07。有人能告诉我如何将double转换为0.07而不是0吗?

您可以为它定义一个自定义的数字facet (numpunct):

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

,然后使用stringstream和locale:

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

问题是默认的区域设置是"C"(代表"Classic"),它使用'。’作为小数分隔符,而excel使用操作系统的小数分隔符。这很可能是一种简单的语言。

  • 要求数据的发起者使用类似英语的语言环境
  • 进行导出
  • 在您的程序中设置基于std::locale("")的区域设置(以便您的程序与系统区域设置一起工作-承认它们是相同的,参见http://en.cppreference.com/w/cpp/locale/locale)
  • 为程序设置基于拉丁语的语言环境(例如IT或ES)
  • 忽略区域设置并将字符串中的","-s替换为"。在把它解释为数字之前。(见std::替换)

这样可以吗?

#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

您可以使用:

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