所以我想使用 for 循环将 10 个不同的数字读入一个文本文件。我的程序的问题是它在输入第 4 个数字时崩溃。我该如何解决?这是我的代码:
#include <stdio.h>
#include <stdlib.h> /* For exit() function */
int main()
{
int x[20], i;
FILE *fptr;
fptr=fopen("line.txt","w");
printf("Enter numbers\n");
for (i=0; i<10; i++){
gets(x[i]);
}
fprintf(fptr,"%d", x);
fclose(fptr);
return 0;
}
最佳答案
你需要使用scanf
,不要使用gets
。 gets
以这种方式使用是不安全的,它读取的是一个字符串,而不是一个数字。无论如何我都会避免 gets
。看看这个关于如何读取整数的答案....
关于c - 如何使用 C 中的 for 循环将数字列表写入文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/36759341/