如何获取getchar()中的最新值?
How to get the latest value in getchar()?
我正在使用 getchar()
函数输入,当我在输入后按回车键时,我得到循环内 c 的值与我输入的一样好,但是当我输入非数字和循环时中断 ... 我输入的最新值是 new line
,其 ASCII 值为 10。
我怎么可能保留数字值。我想要的只是 c
在循环中断后获得数字值
#include<stdio.h>
#include<ctype.h>
main()
{
int c =0;
while(isdigit(c=getchar()))
{
printf("c is : %c\n",c);
}
printf("latest value of c(ASCII) is : %d\n",c);
}
一种方法是添加一个滞后变量并在每次迭代时从 c 写入此变量:
#include<stdio.h>
#include<ctype.h>
int main(int argc, char *argv[])
{
int c = '0', lastchar = 0;
while(isdigit(c))
{
if(!lastchar)
{
printf("c is : %c\n",c);
}
lastchar = c;
c = getchar();
}
printf("latest value of c(ASCII) is : %d\n",lastchar);
return 0;
}
#include<stdio.h>
#include<ctype.h>
int main()
{
int c = 0, last = 0;
while(isdigit(c=getchar()))
{
printf("c is : %c\n",c);
last = c;
}
if (!last)
printf("latest value of c(ASCII) is : %d\n", last);
else
printf("No digits were entered\n");
return 0;
}
你可以做到这一点。
我正在使用 getchar()
函数输入,当我在输入后按回车键时,我得到循环内 c 的值与我输入的一样好,但是当我输入非数字和循环时中断 ... 我输入的最新值是 new line
,其 ASCII 值为 10。
我怎么可能保留数字值。我想要的只是 c
在循环中断后获得数字值
#include<stdio.h>
#include<ctype.h>
main()
{
int c =0;
while(isdigit(c=getchar()))
{
printf("c is : %c\n",c);
}
printf("latest value of c(ASCII) is : %d\n",c);
}
一种方法是添加一个滞后变量并在每次迭代时从 c 写入此变量:
#include<stdio.h>
#include<ctype.h>
int main(int argc, char *argv[])
{
int c = '0', lastchar = 0;
while(isdigit(c))
{
if(!lastchar)
{
printf("c is : %c\n",c);
}
lastchar = c;
c = getchar();
}
printf("latest value of c(ASCII) is : %d\n",lastchar);
return 0;
}
#include<stdio.h>
#include<ctype.h>
int main()
{
int c = 0, last = 0;
while(isdigit(c=getchar()))
{
printf("c is : %c\n",c);
last = c;
}
if (!last)
printf("latest value of c(ASCII) is : %d\n", last);
else
printf("No digits were entered\n");
return 0;
}
你可以做到这一点。