我写这段代码是为了熟悉
getchar().
我采取了路线
while(ch != '\n' && ch != EOF)
ch = getchar();
摘自一本书。对我来说很神秘的是,在第二个 while 循环中使用
getchar()
会导致程序要求我输入。
正在排队
while(ch != '\n' && ch != EOF)
ch = getchar();
使用
getchar()
不会导致程序要求输入。是因为缓冲区里还有信息吗?
我的输入是任何超过
MAX_SIZE
字符数的行。
#include <stdio.h>
#include <string.h>
#define MAX_SIZE 10
int main ()
{
int ch = 0,
i = 0;
char array[MAX_SIZE] = {0};
while(1)
{
i = 0;
while((ch = getchar()) != EOF && ch != '\n' && i < MAX_SIZE - 1)
{
array[i++] = ch;
}
array[i] = '\0';
while(ch != '\n' && ch != EOF)
ch = getchar();
printf("%s\n",array);
for (int i = 0; i < strlen(array) + 1; i++)
printf("[%d]%d\n",i, array[i]);
}
}
有两种不同的情况需要退出第一个 WHILE 情况1) 程序在第一个 WHILE 时退出,因为 ch == EOF 或 ch == ' ' 所以 在进入第二个WHILE之前, ch == EOF 或 ch == ' ' 因此退出条件立即满足,我们不会进入循环
案例2) 程序在第一个 WHILE 时退出,因为 我 == 最大尺寸 - 1 所以 在进入第二个WHILE之前, ch != EOF 和 ch != ' ' 并进入循环清空缓冲区
结论, 在情况 1 中,第一个 WHILE 之后缓冲区为空 在情况 2 中,缓冲区在第二个 WHILE
时被清空