在分函数中用ungetc函数,返回给输入流的空格字符为什么没被下一个getchar函数写入
ungetc函数的疑惑# include <stdio.h>
# include <ctype.h>
# include <stdbool.h>
# include <string.h>
const size_t LENGTH = 50;
void eatspace(void);
bool getinteger(int *n);
char *getname(char *name,size_t length);
bool isnewline(void);
int main(void)
{
int number;
char name[50];
printf("Enter a sequence of integers and alphabetic names:\n");
while(!isnewline())
if(getinteger(&number))
printf("\nInteger value:%8d",number);
else if(strlen(getname(name,LENGTH)) > 0)
printf("\nName:%s",name);
else
{
printf("\nInvalid input:");
return 1;
}
return 0;
}
bool isnewline(void)
{
char ch = 0;
if ((ch = getchar()) == '\n')
{
return true;
}
ungetc(ch,stdin);//这里的ungetc有什么作用?
return false;
}
void eatspace(void)
{
char ch = 0;
while(isspace(ch = getchar()));
ungetc(ch,stdin);//为什么要将非空格字符返回到输入流中?
}
bool getinteger(int *n)
{
eatspace();
int value = 0;
int sign = 1;
char ch = 0;
if((ch = getchar()) == '-')
sign = -1;
else if(isdigit(ch))
value = 10*value + (ch - '0');
else if(ch != '+')
{
ungetc(ch , stdin);//这里的ungetc函数又是如何工作的呢?
return false;
}
while(isdigit(ch = getchar()))
value = 10*value + (ch - '0');
ungetc(ch,stdin);
*n = value*sign;
return true;
}
char *getname(char *name,size_t length)
{
eatspace();
size_t count = 0;
char ch = 0;
while (isalpha(ch = getchar()))
{
name[count++] = ch;
if(count == length - 1)
break;
}
name[count] = '\0';
if(count<length-1)
ungetc(ch,stdin);//这里有为什么要调用这个函数呢?
return name;
}