C++按行读取文本文件,并将每行字符串拆分为double value的坐标值
2014-11-21 21:18
489 查看
目的:按行读取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”如下:
编译:
$ g++ main.cpp -o main
运行:
$ ./main ./test/coordinates.txt
结果:
“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
结果:
相关文章推荐
- C++按行读取文本文件
- C++中利用文件输入对象(即ifstream对象)来读取文本文件中带空格的字符串以及混合输入数字与字符串
- 如何利用C/C++逐行读取txt文件中的字符串(可以顺便实现文本文件的复制)
- [转]C++按行读取文本文件
- 如何利用C/C++逐行读取txt文件中的字符串(可以顺便实现文本文件的复制)
- 如何利用C/C++逐行读取txt文件中的字符串(可以顺便实现文本文件的复制)
- 如何利用C/C++逐行读取txt文件中的字符串(可以顺便实现文本文件的复制)
- 一个C++按行读取Unicode 文本文件的例子
- 如何利用C/C++逐行读取txt文件中的字符串(可以顺便实现文本文件的复制)
- 如何利用C/C++逐行读取txt文件中的字符串(可以顺便实现文本文件的复制)
- VC和C++按行读取文本文件
- C++按行读取文本文件
- [转]C++按行读取文本文件
- C++如何按行读取txt文件并存储到字符串中?
- 收集两个C++写的从文本文件中读取数据保存到数组的程序
- C#快速随机按行读取大型文本文件 - 磊的博客 - sanshi_leilei - 和讯博客
- 从文本文件中读取字符串,再console打印出来
- C++ 简单读写文本文件、统计文件的行数、读取文件数据到数组
- C++读取文本文件
- C和C++分别读取文本文件的方式