读取特定格式的文件

| 我有一个相当简单的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.
}
    
        
#include <cstddef>
#include <limits>
#include <string>
#include <vector>
#include <fstream>

struct coord { double x, y; };

std::vector<coord> read_coords(std::string const& filename)
{
    std::ifstream file(filename.c_str());
    std::size_t line_count;
    file >> line_count;

    // skip first two lines
    file.ignore(std::numeric_limits<std::streamsize>::max(), \'\\n\');
    file.ignore(std::numeric_limits<std::streamsize>::max(), \'\\n\');

    std::vector<coord> ret;
    ret.reserve(line_count);
    std::size_t pointer_num;
    coord c;
    while (file >> pointer_num >> c.x >> c.y)
        ret.push_back(c);
    return ret;
}
在适当的地方添加错误处理。     
        使用while循环
char buffer[256];  

while (! file.eof() )  

   {  

     myfile.getline (buffer,100);  

     cout << buffer << endl;  

   }  
然后您需要解析缓冲区。 编辑: 在eof中使用while循环的正确方法是
while ((ch = file.get()) != EOF) {

}
    

要回复问题请先登录注册