getint函数
函数getint将输入的字符流分解成整数,且每次调用得到一个整数。getint需要返回转换后得到的整数,并且,在到达输入结尾时要返回文件结束标记。
该版本的getint函数在到达文件结尾时返回EOF,当下一个输入不是数字时返回0,当输入中包含一个有意义的数字时返回一个正值。
下面代码用到 getch函数 和 ungetch函数,有何妙处,不解?
int getch(void);
void ungetch(int);
/*getint 函数:将输入中的下一个整型数赋值给*pn */
int getint(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 = getch())
* pn = 10 * *pn + (c - '0');
*pn *= sign;
if(c != EOF) ?这里是干嘛的?
ungetch(c);
return c;
}
#define BUFSIZE 100
char buf[BUFSIZE];
int bufp = 0;
int getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c)
{
if (bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int getch(void);
void ungetch(int);
/*getint 函数:将输入中的下一个整型数赋值给*pn */
int getint(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;
if (c != EOF)
ungetch(c);
return c;
}
#define BUFSIZE 100
char buf[BUFSIZE];
int bufp = 0;
int getch(void)
{
return (bufp > 0) ? buf[--bufp] : getchar();
}
void ungetch(int c)
{
if (bufp >= BUFSIZE)
printf("ungetch: too many characters\n");
else
buf[bufp++] = c;
}
int main()
{
int n, array[10];
for (n = 0; n < 10 && getint(&array[n]) != EOF; n++)
;
for (n = 0; n < 10; n++)
printf("%d\n", array[n]);
return 0;
}
#include <stdio.h>
#include <stdlib.h>
#include <ctype.h>
int getch(void);
void ungetch(int);
/*getint 函数:将输入中的下一个整型数赋值给*pn */
int getint(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 == '+'