【发布时间】:2020-06-11 07:45:06
【问题描述】:
当我尝试使用函数 stod、strtod 和 atof 将从 csv 文件中提取的字符串值转换为双精度值时遇到问题。我只得到值的整数部分。
我用catkin build编译,用来编译ROS中使用的包。 我要转换的值是这个 csv 文件第二行中的 8 个值:
"1","2","3","4","0.0509105","-0.0101653","-0.105985","-0.0534463","Joint Positions"
我将它们提取到字符串向量中:
代码:
ifstream myfile;
myfile.open(path+robot_state_name+".csv");
string str_value;
getline(myfile, str_value); //The first line will be overwriten
vector<string> positions_str;
cout<<"Positions in string format from csv file : "<<endl;
for(int i = 0; i<=nb_of_variables-1; ++i){
getline(myfile, str_value,',');
positions_str.push_back(str_value);
cout<<i<<" : "<<positions_str[i]<<endl;
}
控制台输出:
Positions in string format from csv file :
0 : 1
1 : 2
2 : 3
3 : 4
4 : "0.0509105"
5 : "-0.0101653"
6 : "-0.105985"
7 : "-0.0534463"
然后我使用 std::stod() 将数据转换为双精度。它适用于前 4 个数字,但随后会引发错误。 并不是说 stod() 承认的小数点分隔符就是点,就像在 csv 文件中一样。
代码:
cout<<"Position in double format using stod() : "<<endl;
for(int i = 0; i<=nb_of_variables-1; ++i){
cout<<i<<" : "<<stod(positions_str[i])<<endl;
}
控制台输出:
Position in double format using stod() :
0 : 1
1 : 2
2 : 3
3 : 4
terminate called after throwing an instance of 'std::invalid_argument'
what(): stod
Abandon (core dumped)
stod() 好像不能抓住重点……我也试过 strtod() 和 atof(),最后 4 个值返回 0。
但是当我自己输入值时,它会起作用。
代码:
cout<<"Results of these 3 functions when I type the string values by hand : "<<endl;
positions_str = {"1", "2", "3", "4", "0.0509105", "-0.0101653", "-0.105985", "-0.0534463"};
cout<<"stod() : strtod() : atof() : "<<endl;
char* end_strtod;
for(int i = 0; i<=nb_of_variables-1; ++i){
cout<<stod(positions_str[i])<<" ; "<<strtod(positions_str[i].c_str(), &end)<<" ; "<<atof(positions_str[i].c_str())<<endl;
}
控制台输出:
Results of these 3 functions when I type the string values by hand :
stod() : strtod() : atof() :
1 ; 1 ; 1
2 ; 2 ; 2
3 ; 3 ; 3
4 ; 4 ; 4
0.0509105 ; 0.0509105 ; 0.0509105
-0.0101653 ; -0.0101653 ; -0.0101653
-0.105985 ; -0.105985 ; -0.105985
-0.0534463 ; -0.0534463 ; -0.0534463
我把我为 strtod 和 atof 编写的代码以及函数定义放在那里。
代码:
cout<<"Position in double format using strtod() : "<<endl;
char* end;
for(int i = 0; i<=nb_of_variables-1; ++i){
cout<<i<<" : "<<strtod(positions_str[i].c_str(), &end)<<endl;
}
cout<<"Position in double format using atof() : "<<endl;
for(int i = 0; i<=nb_of_variables-1; ++i){
cout<<i<<" : "<<atof(positions_str[i].c_str())<<endl;
}
控制台输出:
Position in double format using strtod() :
0 : 1
1 : 2
2 : 3
3 : 4
4 : 0
5 : 0
6 : 0
7 : 0
Position in double format using atof() :
0 : 1
1 : 2
2 : 3
3 : 4
4 : 0
5 : 0
6 : 0
7 : 0
非常感谢那些花时间回答的人。
【问题讨论】:
-
这并没有解决问题,而是养成使用有意义的值构造对象的习惯,而不是默认构造它们并立即覆盖默认值。在这种情况下,这意味着将
ifstream myfile; myfile.open(path+robot_state_name+".csv");更改为ifstream myfile(path+robot_state_name+".csv");
标签: c++ string csv double catkin