将字符串转换为以逗号(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;
它们都返回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;
}
相关文章:
- 如何创建一个CMake变量,除非显式重写,否则使用默认值
- 将成员变量添加到共享库中的类中,不会破坏二进制兼容性吗
- 将数组的地址分配给变量并删除
- 为"adjacent"变量赋值时出现问题
- enum是C++中的宏变量还是整数变量
- 在全局变量中保存类的实例以重新创建类(创建"backup")
- 用C++中的一个变量定义一个常量
- 具有奇怪重复模板模式的派生类中的成员变量已损坏
- 你能重载对象变量名本身返回的内容吗
- 绑定派生类方法C++从实例范围之外的分隔 std::function 变量调用
- 如何将整数值解析为逗号分隔字符串中的单独 int 变量?
- 使用运算符将分隔的输入分隔>>变量
- 初始化几个用逗号","分隔的变量
- 逗号分隔在声明变量时如何起作用
- 带分隔标头的类:只能看到成员变量的初始化值
- C++中将不同类型的变量列表连接到逗号分隔字符串的最快方法是什么?
- 逗号分隔变量定义中关系前的序列
- 解析C++中逗号分隔的变量
- 对于二进制数据,哪个性能更高:将整个对象写入文件或分隔变量(无对象)
- 将字符串转换为以逗号(0,07)分隔的双变量