2012-09-17 21 views
0

我讀過,以這種方式閱讀一個txt文件到在C中的多變量維數組++

0,2,P,B 
1,3,K,W 
4,6,N,B 
etc. 

現在我需要在像ARR陣列讀取[X構成的txt文件的需要] [4]
問題是我不知道這個文件裏面的行數。
另外我需要2個整數,並從中2字符...

我想我可以用這個樣本代碼

ifstream f("file.txt"); 
while(f.good()) { 
    getline(f, bu[a], ','); 
} 

obviusly這隻能說明你看懂了什麼,我想我可以使用....但我願意接受任何建議

THX提前和SRY我的工程

回答

5

定義一個簡單struct表示該文件在一個單一的線,並使用這些的 s。使用vector可避免必須明確管理動態分配,並會根據需要進行增加。

例如:

struct my_line 
{ 
    int first_number; 
    int second_number; 
    char first_char; 
    char second_char; 

    // Default copy constructor and assignment operator 
    // are correct. 
}; 

std::vector<my_line> lines_from_file; 

閱讀完整的線,然後將它們分成作爲張貼代碼將允許在例如一個線5逗號分隔的字段,當僅4預計:

std::string line; 
while (std::getline(f, line)) 
{ 
    // Process 'line' and construct a new 'my_line' instance 
    // if 'line' was in a valid format. 
    struct my_line current_line; 

    // There are several options for reading formatted text: 
    // - std::sscanf() 
    // - boost::split() 
    // - istringstream 
    // 
    if (4 == std::sscanf(line.c_str(), 
         "%d,%d,%c,%c", 
         &current_line.first_number, 
         &current_line.second_number, 
         &current_line.first_char, 
         &current_line.second_char)) 
    { 
     // Append. 
     lines_from_file.push_back(current_line); 
    } 

} 
+0

ty @hmjd這正是我要找的。 我在想abuot結構,但我不知道如何將它集成到向量^ – Fed03