2011-06-14 80 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; 
} 

在適當的地方添加錯誤處理。