2009年6月2日
static 变量 P70
Chapter 5 - Pointers and Arrays
Exercise 5-1 |
Exercise 5-2 |
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<ctype.h> #include<stdio.h> int getint(int *pn){ int c, sign; while(isspace(c = getc(stdin))) ; if(!isdigit(c) && c != EOF && c != '+' && c != '-'){ ungetc(c, stdin); return 0; } sign = (c == '-') ? -1 : 1; if(c == '+' || c == '-') c = getc(stdin); for(*pn = 0; isdigit(c); c = getc(stdin)) *pn = 10 * *pn + (c - '0'); *pn *= sign; if(c != EOF) ungetc(c, stdin); return c; }
int main(){ int arr[] = {1, 2, 3, 4, 5}; int n; for(n = 0; n < 5 && getint(&arr[n]) != EOF; n++) ; }
|
在13、14行中间加上这句
if(!isdigit(c)){ ungetc(c, stdin); return 0; }
|
修改后的代码:
#include<ctype.h> #include<stdio.h> int getint(int *pn){ int c, sign; while(isspace(c = getc(stdin))) ; if(!isdigit(c) && c != EOF && c != '+' && c != '-'){ ungetc(c, stdin); return 0; } sign = (c == '-') ? -1 : 1; if(c == '+' || c == '-') c = getc(stdin); if(!isdigit(c)){ ungetc(c, stdin); return 0; } for(*pn = 0; isdigit(c); c = getc(stdin)) *pn = 10 * *pn + (c - '0'); *pn *= sign; if(c != EOF) ungetc(c, stdin); return c; }
int main(){ int arr[] = {1, 2, 3, 4, 5}; int n; for(n = 0; n < 5 && getint(&arr[n]) != EOF; n++) ; }
|
Exercise 5-2. Write getfloat, the floating-point analog of getint. What type does getfloat
return as its function value?
#include<stdio.h> #include<ctype.h>
int getfloat(float *p){ char ch; int sign; while(isspace(ch = getc(stdin))) ; if(!isdigit(ch) && ch != EOF && ch != '.' && ch != '+' && ch != '-'){ ungetc(ch, stdin); return 0; } sign = (ch == '-') ? -1 : 1; if(ch == '+' || ch == '-') ch = getc(stdin); if(!isdigit(ch) && ch != '.'){ ungetc(ch, stdin); } for(*p = 0; isdigit(ch); ch = getc(stdin)) *p = *p * 10 + (ch - '0'); if(ch == '.'){ float tmp; ch = getc(stdin); for(tmp = 0.1; isdigit(ch); ch = getc(stdin)){ *p += tmp * (ch - '0'); tmp *= 0.1; } } *p *= sign; if(ch != EOF) ungetc(ch, stdin); return ch; }
float arr[5] = {1.1, 2.2, 3.3, 4.4, 5.5}; int main(){ int i, tmp; for(i = 0; i < 5 && (tmp = getfloat(arr + i)) && tmp != EOF; i ++) ; }
|
阅读(259) | 评论(0) | 转发(0) |