/*source: stralloc.c*/
#include <stdio.h>
#include <stdlib.h>
int main(void){
char *A;
int max=0;
//need to add error-checking
printf("enter max string length: ");
scanf("%d",&max);
while ((getchar())!='\n');
A=(char *)malloc(max+1); //room for \0
printf("enter string: ");
fgets(A,max,stdin);
printf("Third char is: %c\n",*(A+2));
//printf("Third char is: %c\n",A[2]));
exit(0);
}我从班上得到了这段代码,但有一部分我不明白。while ((getchar())!='\n');在这个函数中做什么?
有人能给我解释一下吗?
发布于 2019-12-09 00:16:59
while ((getchar())!='\n');程序执行继续在这一行,直到它收到新的行字符(即输入)‘\n’。‘'getchar()’方法等待直到收到来自键盘的输入。一旦收到输入,就会与( '\n‘)进行比较,如果输入不是’\n‘,则再次调用getchar()。
发布于 2019-12-08 20:47:35
while ((getchar())!='\n');上面的行意味着,它将一直从输入流中读取,直到遇到换行符'\n'。
https://stackoverflow.com/questions/59239685
复制相似问题