Reading from text file — Separating elements of line
本问题已经有最佳答案,请猛点这里访问。
我有下面的文本文件,尝试从中读取每一行,然后分别存储整数组件和字符串组件。这是文本文件:
1 2 3 4 5 6 7 8 | RUID Name 4325 name1 RUID Name 5432 name2 6530 name3 RUID Name 1034 name4 2309 name5 |
以下是我试图阅读的代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 | 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 name"行,并分离相关行的整数和字符串部分。我尝试过几种策略,但收效甚微。另外,我希望将排序列表的输出写入文本文件。
您应该这样重写循环:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | // 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; } } |