2016-04-25 71 views
-2

我有下面的文本文件,我試圖讀取每一行,然後分別存儲整數組件和字符串組件。這裏是文本文件:從文本文件中讀取 - 分隔行的元素

RUID Name 
4325 name1 
RUID Name 
5432 name2 
6530 name3 
RUID Name 
1034 name4 
2309 name5 

這裏是我試圖與閱讀代碼:

int main() 
{ 
    // Initialize Lists 
    LinkedList list1, list2, list3; 

    // Initialize Counter 
    int counter = 0; 


    // Entry containers 
    const int size = 12; 
    char entry[size]; 
    string name[size]; 
    string RUID[size]; 

    // BEGIN: "read.txt" 
    // Open 
    ifstream studDir; 
    studDir.open("read.txt"); 
    // Read 
    while (studDir.is_open()) 
    { 
     if (studDir.eof()) 
     { 
      cout << "Reading finished" << endl; 
      break; 
     } 

     else if (!studDir) 
     { 
      cout << "Reading failed" << endl; 
      break; 
     } 

     studDir.getline(entry, size); 


     if (entry != "RUID Name") 
     { 
      cout << entry << " " << endl; 
     } 

    } 


    return 0; 
} 

誰能建議,讓我忽略了「RUID名稱」行以及方法分隔相關行的整數和字符串部分。我已經嘗試了幾個很少成功的策略。我也希望將排序列表的輸出寫入文本文件。

回答

1

你應該重寫你的循環是這樣的:

// Entry containers 
const size_t size = 12; 
std::string entry; 
string name[size]; 
string RUID[size]; 
size_t index = 0; 

// ... 

while (index < size && std::getline(studDir,entry)) { 
    if (entry != "RUID Name") { 
     cout << entry << " " << endl; 
     std::istringstream iss(entry); 
     if(!(iss >> RUID[index] >> name[index])) { 
      std::cout << "Reading failed" << endl; 
      break; 
     } 
     ++index; 
    } 
} 
+0

@LokiAstari是啊! –