C ++字符串解析(python style) [英] C++ string parsing (python style)

查看:91
本文介绍了C ++字符串解析(python style)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我喜欢在python我可以做的像:

  points = [] 
for line in open (data.txt):
a,b,c = map(float,line.split(','))
points + = [(a,b,c)]

基本上是读取一行列表,其中每一行表示3D空间中的一个点,点表示为三个数字分开



性能并不是很重要,这个解析只发生一次,因此简单性更重要。



PS我知道这听起来像一个新手的问​​题,但相信我我在D(非常像C ++)写了一个词法分析器,它涉及读取一些文本字符的char和识别代币,

只是这样,回到C ++经过长时间的python,只是让我不想浪费我的时间在这样的事情。

解决方案

d做这样的事情:

  ifstream f(data.txt); 
string str
while(getline(f,str)){
Point p;
sscanf(str.c_str(),%f,%f,%f \\\
,& p.x,& p.y,& p.z);
points.push_back(p);
}

x,y,z必须为浮动。



并包括:

  #include< iostream& 
#include< fstream>


I love how in python I can do something like:

points = []
for line in open("data.txt"):
    a,b,c = map(float, line.split(','))
    points += [(a,b,c)]

Basically it's reading a list of lines where each one represents a point in 3D space, the point is represented as three numbers separated by commas

How can this be done in C++ without too much headache?

Performance is not very important, this parsing only happens one time, so simplicity is more important.

P.S. I know it sounds like a newbie question, but believe me I've written a lexer in D (pretty much like C++) which involves reading some text char by char and recognizing tokens,
it's just that, coming back to C++ after a long period of python, just makes me not wanna waste my time on such things.

解决方案

I`d do something like this:

ifstream f("data.txt");
string str;
while (getline(f, str)) {
    Point p;
    sscanf(str.c_str(), "%f, %f, %f\n", &p.x, &p.y, &p.z); 
    points.push_back(p);
}

x,y,z must be floats.

And include:

#include <iostream>
#include <fstream>

这篇关于C ++字符串解析(python style)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆