2011-06-14 103 views
3

我有一个相当简单的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坐标。我怎样才能有效地做到这一点?

回答

4

我可能会做的只是像我会在C,只用输入输出流:

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

'double x,y; ' – davka 2011-06-14 18:31:49

+0

“就像我会在C”没有iostreams在C. – 2011-06-14 18:31:54

+1

@davka:谢谢 - 纠正。 @jdv:是的,这就是为什么“只使用iostreams” - 即使用iostream而不是'FILE *'。 – 2011-06-14 18:35:23

-1

使用while循环

char buffer[256]; 

while (! file.eof()) 

    { 

    myfile.getline (buffer,100); 

    cout << buffer << endl; 

    } 

,然后你需要分析你的缓冲区。

编辑: 正确使用while循环与EOF是

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

} 
+1

-1:'while(!file.eof())'不可挽回地被破坏。 http://coderscentral.blogspot.com/2011/03/reading-files.html – 2011-06-14 18:28:38

+0

感谢纠正我杰里。 – 2011-06-14 18:40:55

+0

肯定 - 大大改善。 – 2011-06-14 18:42:06

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

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