现在的位置: 首页 > 综合 > 正文

ungetc函数

2013年08月15日 ⁄ 综合 ⁄ 共 824字 ⁄ 字号 评论关闭

ungetc的总结

  对于ungetc是把数字放入回输入端,要不然在处理程序的时候还需要设置变量来进行对这个变量的处理。它在放回的时候是放回在了前面,放在最前面,下次直接第一个将放进去的读取出来。下面是一个示例代码:  

#include<stdio.h>

#include<ctype.h>

int main(){

int ch;

int result=0;

printf("Enter an integer:");

/*Read in and convert number*/

while(((ch=getchar())!=EOF)&&isdigit(ch)){

result = result*10 + ch-'0';

}

if(ch!=EOF)

ungetc(ch,stdin);

printf("Number = %d\nNextcharacter in stream = '%c'",result,getchar());

return 0;

}

输入以及输出结果:

[root@localhost unix_learn]# ./test_ungetc 

Enter an integer:521ab

Number = 521

     从上面这个例子可以看出,在什么情况下,我们会使用ungetc()函数?就是当我们从流中

getc()的结果用于判断,但是读出的结果,如果不符合我们的要求,然而这个结果还有其他用途

这个时候,可以用ungetc()来将读出的结果返回到流中,这样下次就可以继续从流中读取数据。


注意点:

      ungetc 不能连续多次调用。两次 ungetc 调用之间必须至少有一次读操作或者文件指针移动操作

(fseek,rewind  )  ungetc 只影响输入流,而不影响与输入流关联的外存文件。对于以二进制

方式打开的流,ungetc 会使读指针减 1 ,如果当前位置为 0 ,则减 1 后结果 无法预测。紧跟在

 fscanf 后面的 ungetc 也可能会失败,因为 fscanf 中就用到了 ungetc。

抱歉!评论已关闭.