Hatena::Groupcprogramming

C Study Diary

2009-01-09

c5ex1_getint.cpp

14:44

As written, getint treats a + or - not followed by a digit as a valid representation of zero. Fix it to push such a character back on the input.

This program is modified on the getint() in book.

#include <stdio.h>
#include <ctype.h>
#define BUFSIZE 100

char buf[BUFSIZE]; /* buffer for ungetch */
int bufp = 0; /* next free position in buf */

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


/* getint:  get next integer from input into *pn */
int getint(int *pn)
{
	int c, sign, signflag=0;
	while (isspace(c = getch())) /* skip white space */
	;
	if (!isdigit(c) && c != EOF && c != '+' && c != '-') {
		ungetch(c); /* it is not a number */
		return EOF;
	}
	sign = (c == '-') ? -1 : 1;
	if (c == '+' || c == '-') {
		c = getch();
		signflag = 1;
	}	
	/* if sign without number */
	if(!isdigit(c) && c!=EOF) {
		ungetch(c);
		if(signflag) ungetch(((sign==1) ? '+':'-'));
		return EOF;
	}else {	
		for (*pn = 0; isdigit(c); c = getch())
			*pn = 10 * *pn + (c - '0');
		*pn *= sign;
		if (c != EOF)
			ungetch(c);
		return c;
	}
}


int main(){
	
	int pa[10]={}, i=0;
	
	while(getint(&pa[i])!=EOF) {
		pa[i++];
		printf("input: %d\n\n",pa[i-1]);
	}
	printf("char left in buff: %c",getch());
	return 0;
}

Run:

$ ./c5ex1_getint.exe
-23232
input: -23232

+23232
input: 23232

+-232311
char left in buff: +