`
carolaif
  • 浏览: 70263 次
  • 性别: Icon_minigender_2
  • 来自: 大连
最近访客 更多访客>>
社区版块
存档分类
最新评论

C程序设计语言(第二版) 4-7 编写一个函数ungets(),将整个字符串压回到输入中

阅读更多
#include<stdio.h>
#include<string.h>
 
#define BUFSIZE 100 
 
char buf[BUFSIZE]; 
int bufp = 0; 
 
int getch(void); 
void unGetch(int);

/* Getch: get a ( possibly pushed back) character. */ 
int getch(void) 
{ 
     return (bufp > 0) ? buf[--bufp]: getchar(); 
} 
 
/* unGetch: push character back on input. */ 
void unGetch(int c) 
{ 
    if(bufp >= BUFSIZE) 
        printf("\nUnGetch: too many characters\n"); 
    else 
        buf[bufp++] = c; 
}  

void ungets(const char *s) 
{     
  size_t i = strlen(s); //size_t 是unsigned int类型的

  while (i > 0) 
    unGetch(s[--i]); 
}

int main(void) 
{ 
  char *s = "hello, world.  this is a test."; 
  int c; 

  ungets(s); 
  while ((c = getch()) != EOF) 
    putchar(c);                
  return 0; 
} 

 

分享到:
评论

相关推荐

Global site tag (gtag.js) - Google Analytics