下面的输出似乎表明,在getchar()之后调用read ()时,它清除了所有stdin。假设我输入了"Hello\n“:
char buff;
int c;
c=getchar();
printf("%c\n",c); //output H
int res;
res=read(0,&buff,1); //no output, it prompts !!
printf("%c\n",buff);然而,如果我倒置函数,行为是不同的。假设我再次键入"Hello\n“:
char buff;
int res;
res=read(0,&buff,1);
printf("%c\n",buff); output H
int c;
c=getchar();
printf("%c\n",c); output e有人能解释一下这里发生了什么吗?我用的是Mac操作系统
发布于 2022-04-29 12:38:30
下面的输出似乎表明,在getchar()之后调用read ()时,它清除了所有stdin。假设我输入了"Hello\n“:
不是的。将调用混合到getchar() (基于缓冲区的高级例程)和read() (读取所有内容的低级系统调用)。
这就是正在发生的事情:
调用getchar()的
。
您调用的
如果要混合调用,请在getchar()之后使用fread() (它知道并使用stdio缓冲区作为getchar()),而不是read()。
当您反转序列时,read()调用将为您提供已读取的所有内容( read ()中没有缓冲)。当您执行getchar()时,将进行第二个read() (因为缓冲区是空的)来填充该缓冲区。因此,您获得了所有的数据(在第一种情况下,如果在第一次读取之后执行了更多的getchar()s,当然是按错误的顺序得到的)
发布于 2022-04-28 22:38:28
如果您仍然使用此代码输入Hello\n,您将看到:
第一个getchar从stdin读取1个char,其中Hello\n被缓冲,所以它仍然是ello\n。
第二,要求read (这是一个阻塞函数)从stdin读取,因此它等待您输入一些文本(假设您键入"a\n"),它将返回'a‘。
然后,最后一个getchar将从第一步输出中的缓冲条目读取:
H
a
a
e
int main() {
char buff;
int c;
c=getchar();
printf("%c\n",c); //output 'H'
int res;
res=read(0,&buff,1); //it prompts the lettre you just entered here 'a'
printf("%c\n",buff);
c=getchar();
printf("%c\n",c); //output the rest of the buffered stdin 'e'
return 0;
}https://stackoverflow.com/questions/72049341
复制相似问题