一、ungetc函數
ungetc函數是C語言標準庫函數中的一員,其功能是將一個字符退回到流stdin的緩衝區中去,以便於下一次讀取。
其原型如下:
int ungetc(int c, FILE *stream);
其中,參數c是將要被退回到緩衝區的字符,參數stream表示字符流,通常情況下設置為stdin或文件指針。
二、ungetc函數的用法
ungetc函數通常與getc、getchar等函數一起使用,可以用來改變輸入流中字符的讀取順序。
當從stdin讀取到一個字符,但是發現該字符並不是自己所需要的,可以使用ungetc函數將其退回到緩衝區後再使用getc等函數重新讀取。這樣可以方便地實現有條件的字符讀取。
同時,ungetc函數的返回值表示是否成功退回,如果成功,則返回退回的字符,否則返回EOF。
三、ungetch的功能
ungetch是ungetc函數的一種變形,它將字符退回到輸入緩衝區中,可以用來實現更為複雜的輸入邏輯。
在不同的操作系統上,輸入緩衝區的大小可能會有所不同,ungetch可以將字符放回到緩衝區隊列的最前端,因此對於連續輸入的字符,可以實現較為靈活的控制。
以下是ungetch函數的示例代碼:
#define BUFSIZE 100 char buf[BUFSIZE]; int bufp = 0; int ungetch(int c) { if (bufp >= BUFSIZE) { printf("ungetch: too many characters\n"); return 0; } buf[bufp++] = c; return c; }
四、ungetchar
ungetchar是將一個字符退回到輸入流中的簡單函數,與ungetc函數類似,但是只能將1個字符退回到輸入流中。
以下是ungetchar函數的示例代碼:
int ungetchar(int c) { return ungetc(c,stdin); }
五、ungetc函數的用法例子
下面是一個簡單的例子,演示了ungetc函數的用法。
#include <stdio.h> int main() { int c; while ((c = getchar()) != EOF) { if (c == '/') { if ((c = getchar()) == '/') { while ((c = getchar()) != '\n') ; continue; } else if (c == '*') { while ((c = getchar()) != EOF) { if (c == '*') { if ((c = getchar()) == '/') { break; } else { ungetc(c, stdin); } } } continue; } else { ungetc(c, stdin); } } putchar(c); } return 0; }
以上代碼實現的是一個簡單的注釋過濾程序,可以過濾掉C語言中的注釋內容。其中,ungetc函數用於在判斷不是注釋語法的時候將讀取到的字符放回輸入流,以便後續的讀取。
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/153220.html