以特定格式读取文件

时间:2011-06-14 18:19:47

标签: c++ file-io

我有一个相当简单的C ++问题,但是来自C-background我并不是真正意识到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坐标。我怎么能有效地做到这一点?

3 个答案:

答案 0 :(得分:4)

我可能就像在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.
}

答案 1 :(得分:3)

#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;
}

在适当的地方添加错误处理。

答案 2 :(得分:-1)

使用while循环

char buffer[256];  

while (! file.eof() )  

   {  

     myfile.getline (buffer,100);  

     cout << buffer << endl;  

   }  

然后你需要解析你的缓冲区。

编辑: 使用带eof的while循环的正确是

while ((ch = file.get()) != EOF) {

}
相关问题