[英]C Reading numbers from file into array
hey so im trying to read numbers from text file and put them into an array but ive been getting weird numbers when i try to print them. 嘿,即时通讯试图从文本文件中读取数字并将它们放入数组中,但是我在尝试打印它们时却得到了奇怪的数字。 text file looks like:
文本文件如下所示:
45
77
8
...
i guess theres something wrong with the loop im using but i cant seem to find out what. 我猜我使用的循环有问题,但是我似乎找不到答案。 thanks for your help!
谢谢你的帮助!
code: 码:
#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;
}
Try this 尝试这个
while ((status = fscanf(myFile, "%d\n", &myArray[i])) == 1 && i < MAX_ARRAY_SIZE - 1) {
++i;
}
The problem is in your print loop: 问题出在您的打印循环中:
for (a = 0; i < MAX_ARRAY_SIZE; ++i)
There is no guarantee you are reading MAX_ARRAY_SIZE
values. 无法保证您正在读取
MAX_ARRAY_SIZE
值。 Also, if you ar using 'a'
as your loop iterator, then you need to use 'a'
. 另外,如果您使用
'a'
作为循环迭代器,则需要使用'a'
。 Your loop should be: 您的循环应为:
for (a = 0; a < i; ++a)
printf("%d ", myArray[a]);
You also do not need a field-width in your format-specifier , fscanf(myFile, " %d", &myArray[i]))
will do. 您也不需要格式说明符中的字段宽度,
fscanf(myFile, " %d", &myArray[i]))
就可以了。
True... I have not seen print loop code.. Sorry. 是的...我还没有看到打印循环代码。 Problem is in print loop not fscan, please ignore my answer
问题在打印循环中而不是fscan,请忽略我的回答
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.