我正在研究从文本文件读取一系列整数到二维数组中的程序。
该文件包含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