ungetc

头文件:#include<stdio.h>

ungetc()函数用于将一个字符退回到输入流中,这个退回的字符会由下一个读取文件流的函数取得。其原型如下:
    int ungetc(char c,  FILE *stream);

【参数】c为要退回的字符,stream为要退回的输入流。

【返回值】若该函数执行成功,返回非零值;否则,返回0。

举例:下面的示例演示了ungetc()函数的使用,使用该函数将字符退回到输入流中,其代码如下。
   
   
  1. #include<stdio.h>
  2. #include<ctype.h>
  3. int main()
  4. {
  5. int i=0;
  6. char ch;
  7. puts("Input an integer followed by a char:");
  8. // 读取字符直到遇到结束符或者非数字字符
  9. while((ch = getchar()) != EOF && isdigit(ch))
  10. {
  11. i = 10 * i + ch - 48; // 转为整数
  12. }
  13. // 如果不是数字,则放回缓冲区
  14. if (ch != EOF)
  15. {
  16. ungetc(ch,stdin); // 把一个字符退回输入流
  17. }
  18. printf("\n\ni = %d, next char in buffer = %c\n", i, getchar());
  19. system("pause");
  20. return 0;
  21. }
#include<stdio.h>
#include<ctype.h>
int main()
{
    int i=0;
    char ch;
    puts("Input an integer followed by a char:");
    // 读取字符直到遇到结束符或者非数字字符
    while((ch = getchar()) != EOF && isdigit(ch))
    {
        i = 10 * i + ch - 48;  // 转为整数
    }
    // 如果不是数字,则放回缓冲区
    if (ch != EOF)
    {
        ungetc(ch,stdin);  // 把一个字符退回输入流
    }
    printf("\n\ni = %d, next char in buffer = %c\n", i, getchar());
    system("pause");
    return 0;
}
输出结果:
123ab↙
i *= 123, next char in buffer = a

程序开始执行while循环,直到遇到非数字或者结束标识才能往下执行,紧接着判断是不是结束标识,如果不是结束标识则退回键盘缓冲区,在最后输出的时候使用getch()从缓冲区再次获取该字符输出。因为while中使用的是函数getchar(), 所以需要输入字符后按回车键。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值