文章摘要
C++ 读取csv文件
字符串转数据格式(int, float, double)
C++读取csv文件
代码以下,代码详解在注释中:ios
#include
#include
#include
#include
#include
using namespace std;
int main(int argc, char** argv)
{
vector location_x, location_y, location_z;
/* Read data from point_right.csv */
ifstream fin("Topology.csv"); // 打开文件流操做
string line;
while (getline(fin, line)) // 整行读取,换行符“\n”区分,遇到文件尾标志eof终止读取
{
cout << "原始字符串: " << line << endl; // 整行输出
istringstream sin(line); // 将整行字符串line读入到字符串流istringstream中
vector Waypoints; // 声明一个字符串向量
string info;
while (getline(sin, info, ',')) { // 将字符串流sin中的字符读入到Waypoints字符串中,以逗号为分隔符
Waypoints.push_back(info); // 将刚刚读取的字符串添加到向量Waypoints中
}
// Get x,y,z of points and transform to double
string x_str = Waypoints[3];
string y_str = Waypoints[4];
string z_str = Waypoints[5];
//cout << "x= " << x << " " << "y= " << y << " " << "z= " << z << endl;
cout << "Read data done!" << endl;
}
}
上述代码中,Topology.csv为地图坐标的数据文件,读到坐标x,y,z的值为string字符串格式,不符合实际状况且没法使用,应当对其进行字符串转数据格式(int,float,double)spa
字符串转数据格式
对上述代码添加内容:code
......
// Get x,y,z of points and transform to double
string x_str = Waypoints[3];
string y_str = Waypoints[4];
string z_str = Waypoints[5];
double x, y, z;
stringstream sx, sy, sz;
sx << x_str;
sy << y_str;
sz << z_str;
sx >> x;
sy >> y;
sz >> z;
//cout << "x= " << x << " " << "y= " << y << " " << "z= " << z << endl;
cout << "Read data done!" << endl;
location_x.push_back(x);
location_y.push_back(y);
location_z.push_back(z);
}
}
定义double类型变量,使用stringstream流即可以将string字符串转化为数据格式orm