C++按行读取文本文件,并将每行字符串拆分为double value的坐标值

来源:互联网 发布:软件代理商协议 编辑:程序博客网 时间:2024/06/05 08:53

目的:按行读取coordinates.txt文件中的字符串,并将该字符串拆分成double类型的点坐标值。


coordinates.txt”内容如下:

0.61028 0.45567 0.51456 0.59547 0.4640 0.52091 0.58599 0.4961 0.52521 0.57121 0.52022 0.52475 0.5502 0.53852 0.51548
0.54555 0.50853 0.47956 0.54548 0.5103 0.45003 0.54248 0.5078 0.42583 0.53301 0.50517 0.39883 0.5196 0.50449 0.51026


“main.cpp”如下:

#include <iostream>#include <sstream>#include <fstream>#include <string>#include "stdlib.h"int main(int argc, char *argv[]){    if (argc < 2) {      std::cout << "Usage: " << argv[0] << "filename" << std::endl << std::endl;      return -1;    }    // define the file to be read    std::ifstream fin(argv[1], std::ios::in);    // set the buffer size    char line[1024] = {0};    int i = 1;    // read each line    while(fin.getline(line, sizeof(line))){        // set the current line to a stringstream        std::stringstream ss(line);        // split the current line into double values        std::cout<<"The points in the "<<i<<"th line are: "<<std::endl;        while (!ss.eof()) {            double p[3];            std::string token;            for(unsigned dim = 0; dim < 3; dim++){                ss >> token;                p[dim] = atof(token.c_str());            }            std::cout << "<" << p[0] << " " << p[1] << " " << p[2] << ">" << std::endl;        }        std::cout<<std::endl;        i++;    }    fin.close();    return 0;}


编译:

$ g++ main.cpp -o main


运行:

$ ./main ./test/coordinates.txt


结果:




0 0
原创粉丝点击