Created
November 26, 2009 07:19
-
-
Save shaobin0604/243300 to your computer and use it in GitHub Desktop.
Exercise 5-1
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| /* | |
| * Exercise 5-1. 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. | |
| */ | |
| #include <stdio.h> | |
| #include <ctype.h> | |
| int getch(void); | |
| void ungetchar(int); | |
| /* getint: get next integer from stdin into *pn */ | |
| int getint(int *pn) | |
| { | |
| int c, d, sign; | |
| while (isspace(c = getch())) /* skip the white space */ | |
| ; | |
| if (!isdigit(c) && && c != EOF && c != '+' && c != '-') | |
| { | |
| 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 (*p = 0; isdigit(c); c = getch()) | |
| *pn = 10 * *pn + (c - '0'); | |
| *pn *= sign; | |
| if (c != EOF) | |
| ungetch(c); | |
| return c; | |
| } |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment