Added example with variable arrays.
[C-Programming-Examples.git] / ex_5-1.c
blob2b8cad729f9b11f30a587696869ae91f01cf03c3
1 #include <stdio.h>
2 #include <ctype.h>
4 #define BUFSIZE 100
6 char buf[BUFSIZE];
7 int bufp = 0;
9 /*
11 NOTE: getchar and ungetch work in tandem:
13 This allows the user to get a character from standard in, have a look at it
14 and then determine to use it or place it back into a buffer for later use.
16 If this buffer has any chars inside, thise will be poped off first
17 before getting more input from stdin.
21 int getch(void);
22 void ungetch(int);
24 /* reads from buffer if buffer contains chars or calls getchar otherwise */
25 int getch(void)
27 return (bufp > 0) ? buf[--bufp] : getchar();
30 /* places pushed-back characters into a char array shared buffer */
31 void ungetch(int c)
33 if(bufp >= BUFSIZE)
34 printf("ungetch: too many characters\n");
35 else
36 buf[bufp++] = c;
39 /* get next integer from input and put into *pn */
40 int getint(int *pn)
42 int c, sign, signed_num;
44 while(isspace(c = getch()))
46 if(!isdigit(c) && c != EOF && c != '+' && c != '-')
48 ungetch(c);
49 return 0;
52 sign = (c == '-') ? -1 : 1;
53 if((signed_num = (c == '+' || c == '-')))
54 c = getch();
55 if(!isdigit(c))
57 ungetch(c);
58 if(signed_num)
59 ungetch((sign == -1) ? '-' : '+');
60 return 0;
63 for(*pn = 0; isdigit(c); c = getch())
64 *pn = 10 * *pn + (c - '0');
65 *pn *= sign;
66 if(c != EOF)
67 ungetch(c);
68 return c;
71 int main()
73 int n[5];
74 int retval = '\0';
76 retval = getint(n);
78 printf("Retval: %c\n", retval);
80 int i;
81 for(i = 0; i < 5; i++)
83 printf("%d", n[i]);
87 printf("\n");
89 return 1;