我有一个相当简单的 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/