2012-11-16 35 views
0

我有帶數字的文件。從數組中的文件中放入數字

3 
2 15 41 
4 1 2 3 4 
3 22 11 24 

第一行顯示其他行如何存在(最大100)。 號在行不能含有超過50

在數字線需要被放入數組是這樣的:

line[lineNum][num] 

我用C++新,我問要做到這一點最簡單的方式更多鈔票。我試過:

#include <iostream> 
#include <fstream> 
#include <string> 

using namespace std; 

int main(int argc, char *argv[]) 
{ 
    int kiek; 
    string str[100][50]; 
    string line; 
    int a = 0; 
    int b = 0; 

    ifstream failas("Duom1.txt"); 

    if (failas.is_open()) 
    {      
     while (failas) 
     { 
      if (a == 29) 
      { 
        a = 0; 
        b++; 
      } 

      getline(failas, str[a][b], ' '); 

     } 

     a++; 
    } 

    cout << str[0][0] << endl; 
} 
+0

明顯的問題。如果你有一個數字文件,你爲什麼說'string str [100] [50]'? 'int str [100] [550]'似乎是更好的事情。 – john

回答

2

逐行讀取文件,然後解析每一行。

if (failas.is_open()) 
{ 
    // read first line 
    string num_lines; 
    std::getline(failas, num_lines); 
    // read lines 
    for (int i = 0; std::getline(failas, line); ++i) 
    { 
     // parse line and insert into array 
     std::istringstream is(line); 
     string number; 
     for (int j = 0; is >> number; ++j) 
      str[i][j] = number; 
    } 
} 

更好的方法雖然是使用std::vector而不是數組:

std::vector<std::vector<int> > all_nums; 
... 
// read first line 
string num_lines; 
std::getline(failas, num_lines); 
// read lines 
while (std::getline(failas, line)) { 
    // parse line and insert into vector 
    std::istringstream is(line); 
    int number; 
    std::vector<int> line_nums; 
    while (is >> number) 
     line_nums.push_back(number); 

    // add line to vector 
    all_nums.push_back(line_nums); 
} 
相關問題