M
mdh
Hi All,
May I ask this. The exercise 5-1 asks one to correct an input in which
a non-digit follows a + or - . T & G show this:
/****/
if ( c == '+' || c == '-'){
d=c;
if ( !isdigit(c=getch())){
if (c !=EOF)
ungetch(c);
ungetch(d);
return d;
}
}
My question is: Does this not lead to an endless loop? (That's what I
seem to get) Or is this just illustrating something?
Complete code below.
Thanks in advance.
/****/
#include <stdio.h>
# include <ctype.h>
# define SIZE 10
int main () {
int getint ( int *);
int p, i, arr[SIZE];
for (p=0; getint( &arr[p]) != EOF; p++);
for ( i=0; i< SIZE; i++)
printf( "Converted input in Array idx(%d) = %d\n", i, arr);
return 0;
}
/*******/
int getch(void);
void ungetch(int);
int getint(int *px){
int c, d, sign;
while ( isspace( c= getch())) ;
if ( ! isdigit (c) && c != '+' && c != '-' && c != EOF) {
ungetch(c);
return 0;
}
sign = (c=='-') ? -1:1;
if ( c == '+' || c == '-'){
d=c;
if ( !isdigit(c=getch())){
if (c !=EOF)
ungetch(c);
ungetch(d);
return d;
}
}
for (*px=0; isdigit(c); c=getch())
*px=*px * 10 + (c - '0');
*px=*px * sign;
if ( c != EOF)
ungetch(c);
return c;
}
/*********/
#define BUFSIZE 10
char buf[BUFSIZE];
int bufp=0;
int getch(void){
return (bufp > 0) ? buf[--bufp]: getchar();
}
void ungetch(int c){
if ( bufp < BUFSIZE)
buf[bufp++] = c;
else
printf("Error: ungetch...buffer overflow");
}
May I ask this. The exercise 5-1 asks one to correct an input in which
a non-digit follows a + or - . T & G show this:
/****/
if ( c == '+' || c == '-'){
d=c;
if ( !isdigit(c=getch())){
if (c !=EOF)
ungetch(c);
ungetch(d);
return d;
}
}
My question is: Does this not lead to an endless loop? (That's what I
seem to get) Or is this just illustrating something?
Complete code below.
Thanks in advance.
/****/
#include <stdio.h>
# include <ctype.h>
# define SIZE 10
int main () {
int getint ( int *);
int p, i, arr[SIZE];
for (p=0; getint( &arr[p]) != EOF; p++);
for ( i=0; i< SIZE; i++)
printf( "Converted input in Array idx(%d) = %d\n", i, arr);
return 0;
}
/*******/
int getch(void);
void ungetch(int);
int getint(int *px){
int c, d, sign;
while ( isspace( c= getch())) ;
if ( ! isdigit (c) && c != '+' && c != '-' && c != EOF) {
ungetch(c);
return 0;
}
sign = (c=='-') ? -1:1;
if ( c == '+' || c == '-'){
d=c;
if ( !isdigit(c=getch())){
if (c !=EOF)
ungetch(c);
ungetch(d);
return d;
}
}
for (*px=0; isdigit(c); c=getch())
*px=*px * 10 + (c - '0');
*px=*px * sign;
if ( c != EOF)
ungetch(c);
return c;
}
/*********/
#define BUFSIZE 10
char buf[BUFSIZE];
int bufp=0;
int getch(void){
return (bufp > 0) ? buf[--bufp]: getchar();
}
void ungetch(int c){
if ( bufp < BUFSIZE)
buf[bufp++] = c;
else
printf("Error: ungetch...buffer overflow");
}