当尝试使用stod,strtod和atof函数将从csv文件提取的字符串值转换为两倍时,出现了问题。我只得到值的整数部分。
我使用catkin构建进行编译,其中wich用于构建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 overwritte
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()将数据转换为double。它适用于前四个数字,但随后引发错误。并非像csv文件中那样,由stod()接受的小数点分隔符就是重点。
代码:
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。
但是当我自己输入值时,它会起作用。
Code:
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
非常感谢那些花时间回答的人。
您必须删除字符串中的引号,您可以这样操作:
str.erase(std::remove(str.begin(), str.end(), '"'), str.end());
也使用for(int i = 0; i<=nb_of_variables-1; ++i)
,您正在for循环之前增加i值,这意味着将永远不会调用position_str [0]。试试
for(int i = 0; i<positions_str.size(); i++){
str.erase(std::remove(positions_str[i].begin(), positions_str[i].end(), '"'), positions_str[i].end());
getline(myfile, str_value,',');
positions_str.push_back(str_value);
cout<<i<<" : "<<positions_str[i]<<endl;
}