ungetc

来源:互联网 发布:网络推广怎么安排工作 编辑:程序博客网 时间:2024/05/21 23:27
头文件:#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(), 所以需要输入字符后按回车键。
0 0
原创粉丝点击