C语言初学者,到fscanf和fprintf遇到一些问题。
下面程序words数组只能储存40个字符,为什么在这个程序中,超过40个字符仍是能够正常输出的呢?
尤其是在这个while循环,while (fscanf(fp," %s",words) == 1),在这里文件中的字符是超过40个的,但仍是正常输出了,还有,%s前加了一个空格,这又是什么意思? 请高手帮助一下,谢谢!
#include <stdio.h>
#include <stdlib.h>
#define MAX 40
int main(void)
{
FILE *fp;
char words[MAX];
if ((fp = fopen("wordy", "a+")) == NULL)
{
fprintf(stdout,"Can't open \"words\" file.\n");
exit(1);
}
puts("Enter words to add to the file; press the Enter");
puts("key at the beginning of a line to terminate.");
while (gets(words) != NULL && words[0] != '\0')
fprintf(fp, " %s", words);
puts("File contents:");
rewind(fp);
while (fscanf(fp," %s",words) == 1)
puts(words);
if (fclose(fp) != 0)
fprintf(stderr,"Error closing file\n");
return 0;
}
但是words数组最大只能储存40个字符啊,循环输入还不是超出了总长度?
追答每一次循环都会再建一个word数组,与之前的已经没有关系了
追问为什么每次循环都会新建一个数组,可以讲详细点吗?我是初学者~