c语言读取csv 宽字符串,C++ 读csv字符串并转化为数据格式

文章摘要

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值