views:

425

answers:

1
+1  Q: 

getint and getch

"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."

Ok, well this is the original version:

int getint2(int *pn)
{
    int c, sign;

    while(isspace(c=getch()))
         ;

    if(!isdigit(c) && c!= EOF && c!= '+' && c!= '-') {
          ungetch(c);
          return 0;
    }

    sign = (c == '-') ? -1 : 1;

    if(c == '+' || c == '-') {
       c = getch();
    }

    for(*pn = 0; isdigit(c); c = getch())
        *pn = 10 * *pn + (c - '0');

    *pn *= sign;
    ungetch(c);
    return c;
}

And i edited this way:

int getint2(int *pn)
{
    int c, sign;

    while(isspace(c=getch()))
         ;

    if(!isdigit(c) && c!= EOF && c!= '+' && c!= '-') {
          ungetch(c);
          return 0;
    }

    sign = (c == '-') ? -1 : 1;

    if(c == '+' || c == '-') {
       c = getch();

       if(!isdigit(c)) {
         ungetch(c);
         return 0;
       }
    }

    for(*pn = 0; isdigit(c); c = getch())
        *pn = 10 * *pn + (c - '0');

    *pn *= sign;
    ungetch(c);
    return c;
}

So im not sure what did the author want. Should i unget the +/- aswell, or just the character after it? Should i return 0 in case there's no digits after +/- or -1?

I also have a question about getch and ungetch functions: since EOF on my sistem is -1, this is how i wrote getch and ungetch:

int buf = EOF;

int getch()
{
    int temp;

    if(buf == -2)
        return EOF;

    if(buf == EOF) 
        temp = getchar();
    else
    {
        temp = buf;
        buf = EOF;
    }

    return temp;
}

void ungetch(int c)
{
     if(c == EOF) 
        buf = -2;

     buf = c;
}

So i was told by some people that EOF can be -2. What should i do to avoid this sort of 'problem'.

+1  A: 

To answer your second question, about EOF and -2, I can think of a couple of solutions:

  • you could have an array of characters in the "buffer", and an "index" in the position (i.e., have a rudimentary stack). I believe that arrays are introduced in K&R by that point. That will give you flexibility in that you can ungetch() more than one character. An added advantage of this scheme is that your code in part 1, where you might need to ungetch() twice, becomes easier as well.
  • you could store the 'state' in another int variable, such as int buffered = 0;, and then getch() would return buf only when buffered == 1. ungetch() sets buffered = 1, getch() sets buffered = 0:
static int buf;
static int buffered = 0;

int getch()
{
    if (buffered) {
        buffered = 0;
        return buf;
    }
    return getchar();
}

void ungetch(int c)
{
    buffered = 1;
    buf = c;
}
Alok