1
我試圖實現的是,從.txt
文件中逐行讀取數據,使用getline()
,並將其保存爲字符串變量inVal
。然後,我想通過將其傳遞給成員函數ArrayBag.add(value)
將字符串中的每個單獨數字保存到objects數組中的單個元素。到目前爲止,我已經能夠讀取數據到inVal
罰款,但沒有任何我已經嘗試能夠轉換並保存字符串中的數字,包括getline()
後面的代碼。請任何指導或提示將不勝感激。如何將字符串中的整數存入數組中的元素
的.txt
文件看起來像這樣:
3 4 5 7 5 16 7 12 11 12 3 9 9 8 1 12
15 4 3 6 1 12 3 12 7 8 19 9 11 12 8 5 -4 -100
我至今是香港專業教育學院編寫的代碼是這樣的:
void readInv(ArrayBag &ArrayBag1, ArrayBag &ArrayBag2) {
//ArrayBag1 and ArrayBag2 are objects of class ArrayBag
std::string inVal;
//value to hold each line in file
std::ifstream readFile;
readFile.open("setInventory.txt"); //"setInventory.txt" is the txt file being read from.
if (readFile.is_open()) {
std::cout << "File is being read." << std::endl;
while(!readFile.eof()) {
getline(readFile, inVal);
for(int i = 0; i < inVal.size(); i++) {
std::cout << inVal[i] << std::endl;
ArrayBag1.add(inVal[i] - '0');
//ArrayBag1.add() is the public member function used to add the
//passing value to the private member array.
}
}
}
}
關閉主題(但將解決即將發佈的錯誤):[爲什麼iostream :: eof在循環條件之內在考慮錯誤?](https://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – user4581301
可能重複[逐行讀取文件](https: //stackoverflow.com/questions/7868936/read-file-line-by-line)。具體回答1選項2. – user4581301
是否有一個原因,你不能使用'std :: vector'這個?向量比數組好得多。 – Sailanarmo