C从文件中读取数字到数组
问题描述:
嘿所以我试图从文本文件中读取数字,并将它们放入数组中,但是当我尝试打印它们时,我的数字已变得奇怪。文本文件看起来像:C从文件中读取数字到数组
45
77
8
...
我猜有件事错的循环I M使用,但我不能似乎发现了什么。 感谢您的帮助!
代码:
#define MAX_ARRAY_SIZE 20
int main(int argc, char * argv[])
{
FILE *myFile;
int myArray[MAX_ARRAY_SIZE];
//char filename[32];
//printf("enter filename\n");
//scanf("%s", filename);
myFile = fopen("asdf.txt", "r");
if (!myFile) {
printf("cant open file\n");
return 1;
}
int status;
int i = 0;
while ((status = fscanf(myFile, "%2d", &myArray[i])) == 1 && i < MAX_ARRAY_SIZE - 1) {
++i;
}
fclose(myFile);
int a;
for (a = 0; i < MAX_ARRAY_SIZE; ++i) {
printf("%d ", myArray[i]);
}
printf("\n");
return 0;
}
答
的问题是在您的打印循环:
for (a = 0; i < MAX_ARRAY_SIZE; ++i)
谁也不能保证你正在阅读MAX_ARRAY_SIZE
值。另外,如果你使用'a'
作为循环迭代器,那么你需要使用'a'
。你的循环应该是:
for (a = 0; a < i; ++a)
printf("%d ", myArray[a]);
你也并不需要场宽度在格式说明符,fscanf(myFile, " %d", &myArray[i]))
会做。
+0
是啊:我以前使用“我”,并忘记将其全部更改为:D thx – Nils
答
试试这个
while ((status = fscanf(myFile, "%d\n", &myArray[i])) == 1 && i < MAX_ARRAY_SIZE - 1) {
++i;
}
答
真的......我还没有看到打印循环代码..对不起。 问题是在打印循环中不是fscan,请忽略我的回答
+0
您可以编辑您的答案以根据需要进行更改。不要提交其他答案。 –
'for(a = 0; a BLUEPIXY