读书人

不是说ungetc(ch, stdin)中ch如其没有

发布时间: 2013-07-08 14:13:00 作者: rapoo

不是说ungetc(ch, stdin)中ch如果没有读出来不是放不进去新的字符吗?
下面是个练习ungetc()小程序:

#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"

int main(void)
{

char ch, ch1, ch2;
scanf("%c", &ch);
ch1 = getchar();
ungetc(ch, stdin);
ungetc(ch1, stdin);
ch2 = getchar();
printf("%c\n", ch2);

return 0;
}


比如我在黑窗口中输入whale,我想应该是ch = w;ch1 =h;了,再把ch放回缓冲区中,又把ch1放回缓冲区中,因为ch放回去后没有及时读取,应该ch1是放不回去的,那么应该ch2 = w才是,因为ch2要到缓冲区读取数据,那这个数据应该是w.但是结果是ch2 = h;为什么?
[解决办法]

int
main (int argc, char **argv)
{
ungetc ('\n', stdin);
ungetc ('c', stdin);
ungetc ('b', stdin);
ungetc ('a', stdin);

printf ("%c", getc(stdin));
printf ("%c", getc(stdin));
printf ("%c", getc(stdin));
printf ("%c", getc(stdin));
return 0;
}

把这程序看懂了, 你就明白了
[解决办法]
ungetc(ch1, stdin);
ch2 = getchar();

所以实际上ch2=ch1,为字符h

引用:
下面是个练习ungetc()小程序:

#include "stdafx.h"
#include "stdio.h"
#include "stdlib.h"
#include "string.h"

int main(void)
{

char ch, ch1, ch2;
scanf("%c", &ch);
ch1 = getchar();
ungetc(ch, stdin);
ungetc(ch1, stdin);
ch2 = getchar();
printf("%c\n", ch2);

return 0;
}


比如我在黑窗口中输入whale,我想应该是ch = w;ch1 =h;了,再把ch放回缓冲区中,又把ch1放回缓冲区中,因为ch放回去后没有及时读取,应该ch1是放不回去的,那么应该ch2 = w才是,因为ch2要到缓冲区读取数据,那这个数据应该是w.但是结果是ch2 = h;为什么?


[解决办法]
引用:
getmonyinfo,我其实之前看过像您的类似的程序,所以我才对我的程序结果有疑问。您看看我分析得对不对?
您的程序将四个字符先后送回缓冲区,然后再读取,实际上因为'\n'送回后,没有及时被读取,后面三个是放不回去的,所以后面 四个显示在黑窗口中只有显示一个换行符,当然在黑窗口中是什么也看不到的,然后要求输入字符。与之前送回去的b c a没有关系,因为它们送不回去。

正因为我这样想,所以我才认为我的程序也应该ch2应该读取最初送回去的ch,而不是ch1。
我想我分析得肯定有误,但是我自己认识不到,请帮我指出。


你有没有运行我的程序? "后面三个是放不回去的"这怎么可能, stdin是标准输入流,他是有缓冲区的。ungec的行为类似于栈, 先进后出,所以ungec 依次压入\ncba, 输出时顺序也就成了abc\n
[解决办法]
最后ungetc的值最先读出来。
[解决办法]
A character is virtually put back into an input stream, decreasing its internal file position as if a previous getc operation was undone.
[解决办法]
在 MSDN 上面有这么一段话:
Results are unpredictable if ungetc is called twice without a read or file-positioning operation between the two calls

而且 你可以 测试 ugetc 的返回值, 其实 连续的第二次 调用 ugetc 返回 EOF 了 表示失败了!!!
[解决办法]
一句话,这个缓冲区是一个栈而非一个队列。get类似于pop,unget类似于push,能明白吗

读书人网 >C语言

热点推荐