Getint function

Hello,

I have this getint function I need to test

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55

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

/* Implementation */

static char buf[BUFSIZE];
static int bufp = 0;

int getch(void) {return (bufp > 0) ? buf[--bufp] : getchar();}

int ungetch(int c)  
{
    if (bufp >= (int)sizeof(buf))
        return EOF;
    else
        buf[bufp++] = c;
}


/* getint: get next integer from input into *pn */

int getint(int *pn)
{
   int c, sign;
   
   while (isspace(c = getch()))       /* skip white space */
        ;

   if (!isdigit(c) && c!= EOF && c!= '+' && c!= '-') {
   ungetch(c);      /* it's not a number */
   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;
  
  if (c != EOF)
      ungetch(c);
  return c;
  
}





All programming must be done in C, but how could I test this?
The original getint treated + or - not followed by a digit as a valid representation of zero. Now I fixed it to push such character back on the input.


can you elaborate your problem more ?
He wants to test his function.

Try it with different inputs:

7
-7
+7

123
-123
+123

2147483647
-2147483647
+2147483647

fail:
2147483648
+2147483648
-2147483648

4000000000

+
-

123a
74-
3.14

abc
-abc

+-

etc

Hope this helps.
Can you provide a complete program please? To test, whether the character is pushed successfully back on the input, I think I need something like this:


1
2
3
4
5
6
7
8
9

static void pushback(void)
{

  printf(" L = %d: [%.*s]\n", bufp, bufp, buf]

}




Orherwisely it makes no sense for me.
Last edited on
I'm not going to debug your code for you.
Topic archived. No new replies allowed.