函數應該從文本文件中讀取整數。第一個數字會告訴輸入文件中有多少個數字。動態分配的整數數組在功能結束時自行刪除
我首先初始化接收整數爲NULL的指針,但由於某種原因,當函數結束並返回時,它仍然指向NULL。
bool readFileToArray(const char* fileName, int *arr, int &size)
{
ifstream input = ifstream(fileName);
int i, num;
// check if file opened successfully and allow only non negative integers to be read as num of elements
if (!input.is_open() || !(input >> size) || size < 0)
return wasError(input);
// allocate an array of 'size' size
arr = new int[size];
for (i = 0; i < size; i++)
{
input >> num;
// check for illegal input
if (input.fail())
return wasError(input);
else
arr[i] = num;
}
// given size and actual size mismatch
if (i != size || !input.eof())
return wasError(input);
// if file opening and writing ended successfully
return false;
}
由於玩世不恭,我正在用原始數組編寫此版本,以顯示原始數組與STL的比較 – Quaker