Von*_*nti 26 c arrays file scanf
我是编程菜鸟所以请耐心等待.
我正在尝试将文本文件中的数字读入数组.文本文件"somenumbers.txt"只包含16个数字,如此"5623125698541159".
#include <stdio.h>
main()
{
FILE *myFile;
myFile = fopen("somenumbers.txt", "r");
//read file into array
int numberArray[16];
int i;
for (i = 0; i < 16; i++)
{
fscanf(myFile, "%d", &numberArray[i]);
}
for (i = 0; i < 16; i++)
{
printf("Number is: %d\n\n", numberArray[i]);
}
}
Run Code Online (Sandbox Code Playgroud)
该计划不起作用.它汇编但输出:
编号是:-104204697
数字是:0
编号是:4200704
编号是:2686672
编号是:2686728
编号是:2686916
编号是:2004716757
编号是:1321049414
数字是:-2
编号是:2004619618
编号是:2004966340
编号是:4200704
编号是:2686868
编号是:4200798
编号是:4200704
编号是:8727656
进程返回20(0x14)执行时间:0.118秒按任意键继续.
BLU*_*IXY 28
改成
fscanf(myFile, "%1d", &numberArray[i]);
Run Code Online (Sandbox Code Playgroud)
hac*_*cks 12
5623125698541159被视为单个数字(超出int大多数架构的范围).您需要在文件中写入数字
5 6 2 3 1 2 5 6 9 8 5 4 1 1 5 9
Run Code Online (Sandbox Code Playgroud)
16个数字.
如果您的文件有输入
5,6,2,3,1,2,5,6,9,8,5,4,1,1,5,9
Run Code Online (Sandbox Code Playgroud)
然后改变%d你的符fscanf来%d,.
fscanf(myFile, "%d,", &numberArray[i] );
Run Code Online (Sandbox Code Playgroud)
经过一些修改后,您的完整代码如下:
#include <stdio.h>
#include <stdlib.h>
int main(){
FILE *myFile;
myFile = fopen("somenumbers.txt", "r");
//read file into array
int numberArray[16];
int i;
if (myFile == NULL){
printf("Error Reading File\n");
exit (0);
}
for (i = 0; i < 16; i++){
fscanf(myFile, "%d,", &numberArray[i] );
}
for (i = 0; i < 16; i++){
printf("Number is: %d\n\n", numberArray[i]);
}
fclose(myFile);
return 0;
}
Run Code Online (Sandbox Code Playgroud)