2012-10-05 22 views
0

我知道解析類似這樣的問題在這裏有很多問題,但是在搜索了一段時間之後,我找不到一個答案幫助了我,所以希望我沒有問過之前已經回答了一百萬次的問題。如何在C++中將文本文件解析爲結構的不同元素?

我有一個文本文件,它看起來像這樣:

1 14 100 
3 34 200 
2 78 120 

第一個數字是一個ID號,第二個是一個時代,第三個數字是重量。 (這些是任意的描述)我也有一個結構,看起來像這樣:

struct myData{ 
    int ID; 
    int age; 
    int weight; 
}; 

創建myData的結構數組後,我該如何通過文字迭代,最終使我結束了每一行的每個元素文本文件在數組的一個索引中?例如,填充陣列與所述文本文件中的元素之後,我應該能夠說

cout << myData[0].ID << ", " << myData[0].age << ", " << myData[0].weight << "\n"; 

,它應該打印出「1,14,100」和它應該打印的「3,78, 120「,如果索引在上面的代碼行中是2的話。我嘗試尋找其他人使用getLine()或get()等的例子,但我似乎無法得到它的竅門。我希望我收集了關於我的問題的足夠信息,以便本網站上的嚮導可以輕鬆回答。提前致謝!

+5

在我看來,這是家庭作業,所以我更誘惑說:「你還有什麼嘗試,你卡在哪裏?」 – ereOn

+0

閱讀關於[序列化/反序列化]的概念(http://en.wikipedia.org/wiki/Serialization)。之後,粘貼你正在使用的代碼;) –

+0

查找['std :: ifstream'](http://en.cppreference.com/w/cpp/io/basic_ifstream),[輸入操作符>> '](http://en.cppreference.com/w/cpp/io/basic_istream/operator_gtgt)和['std :: vector'](http://en.cppreference.com/w/cpp/container/vector )。當然還有'while'和'for'循環。 –

回答

4

怎麼是這樣的:

struct myData 
{ 
    int ID; 
    int age; 
    int weight; 

    // Add constructor, so we can create instances with the data 
    myData(int i, int a, int w) 
     : ID(i), age(a), weight(w) 
     {} 
}; 

std::vector<myData> input; 
std::ifstream file("input.txt"); 

// Read input from file 
int id, age, weight; 
while (file >> id >> age >> weight) 
{ 
    // Add a new instance in our vector 
    input.emplace_back(id, age, weight); 

    // Skip over the newline, so next input happens on next line 
    std::ignore(std::numeric_limits<std::streamsize>::max(), '\n'); 
} 

// Close the file after use 
file.close(); 

// Print all loaded data 
for (auto data : input) 
{ 
    cout << "ID: " << data.ID << ", age: " << data.age << ", weight: " << data.weight << '\n'; 
} 
+0

謝謝!我最終做的並不完全接近你在這裏的內容,但是你的代碼片段確實幫助我得到了我需要的答案。 – ahabos

1

您可以使用包括文件: #include <fstream> ,只是做類似

std::ifstream infile("file.txt"); 
    int a, b, c; 
    while (infile >> a >> b >> c) 
    { 
     // process (a,b,c) 
    } 

東西不要忘了關閉流。

0

打開該文件,並通過它來讀取所有行:

//Opening File 
FILE *trace; 
trace=fopen("//path//to//yourfile","r"); 

// Read the file 
myData list[N]; 
int count=0; 
while(!feof(trace)){ 
    fscanf(trace,"%d %d %d\n", &myData[count].ID, &myData[count].age, &myData[count].weight); 
    count++; 
} 

// now you have an array of size N go through it and print all 
for(int i=0; i<count; i++) 
    printf("%d %d %d\n", myData[i].ID, myData[i].age, myData[i].weight); 
+1

此問題標記爲C++,那麼爲什麼你使用C代碼回答? –

+0

Ooops。你是對的! – ahmad