c++ - 以特定格式读取文件

标签 c++ file-io

我有一个相当简单的 C++ 问题,但是来自 C 背景的我并不真正了解 C++ 的所有 I/O 功能。那么问题来了:

我有一个特定格式的简单 .txt 文件,文本文件如下所示:

123 points are stored in this file
pointer number | x-coordinate | y-coordinate
0      1.123      3.456
1      2.345      4.566
.....

我想读出坐标。我怎样才能做到这一点? 第一步很好:

int lines;
ifstream file("input.txt");
file >> lines;

这会将文件中的第一个数字(即示例中的 123)存储在行中。现在我想遍历文件并只读取 x 和 y 坐标。我怎样才能有效地做到这一点?

最佳答案

我可能会像在 C 中那样做,只是使用 iostreams:

std::ifstream file("input.txt");

std::string ignore;
int ignore2;
int lines;
double x, y;

file >> lines;
std::getline(ignore, file);   // ignore the rest of the first line
std::getline(ignore, file);   // ignore the second line

for (int i=0; i<lines; i++) {
     file >> ignore2 >> x >> y;    // read in data, ignoring the point number
     std::cout << "(" << x << "," << y << ")\n";   // show the coordinates.
}

关于c++ - 以特定格式读取文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6348142/

相关文章:

c++ - 默认移动构造函数

c - fprintf覆盖C中的其他数据

c - malloc 还是不malloc,这是个问题!

Java 字符串中断文件操作

c++ - 将成员函数添加到绑定(bind)到 Lua 的 C++ 类

c++ - 是否可以根据构建配置更改 Eclipse CDT 中的代码?

c++ - 添加了对 .lib 项目的引用 - 项目不使用 .cpp 文件?

c++ - C++ Concurrency in action 中关于parallel_accumulate 的困惑

java - java中如何替换文件内容?

c# - C#-fu-以功能样式查找常用单词