我正在研究從文本文件讀取一系列整數到二維數組中的程序。
該文件包含40行81個數字,它們之間沒有空格。file.get()在循環後返回隨機數C++
問題是,當我在循環完成後關閉數組時,它會在預期輸出之前在array[0][0]
和array[0][1]
之間輸出2個隨機數。我認爲這與換行符/回車符有關。循環的第一次迭代運行完美。下面是代碼:
#include <cstring>
#include <cstdlib>
#include <iostream>
#include <fstream>
using namespace std;
int main()
{
int array[9][9];
//Open file:
fstream ifile;
ifile.open("numbers.txt", ios::in);
if (ifile.fail())
{
cout << "Could not open numbers.txt" << endl;
return -1;
}
while (!ifile.eof())
{
for(int i=0; i<9; i++)
{
for(int j=0; j<9; j++)
{
int n = ifile.get();
if(isdigit(n))
{
array[i][j] = n - '0';
}
cout<<"array ["<<i<<"]["<<j<<"] is "<<array[i][j]<<endl;
}
} cout<<"This is a test"<<endl;
}
return 0;
}
你的輸入文件是怎樣的? – 2012-04-05 16:29:25
1)你不測試'file.get()'是否成功。 2)即使'n'不是一個數字,你也會增加'j',並且3)**請**提供一個簡短而完整的程序,用來證明你所遇到的錯誤。請參閱http://sscce.org/。 – 2012-04-05 16:31:50
@KornelKisielewicz這是一個包含40行81個數字的文件,它們之間沒有空格 – adohertyd 2012-04-05 16:32:06