关于getchar()

来源:百度知道 编辑:UC知道 时间:2024/07/04 01:20:27
C语言中关于getchar的用法
我想写一个程序:先用getchar读入,如果不是回车(\n)就读入数据,并判断是否是实数
但是想继续判断下一个数,要再向键盘输入,请问这里的getchar应该怎样使用(读入一行并判断我会,但是怎样编写可以让他读入下一行判断下一个数)
虽然在这里谈分不好,但是绝对不少于50分
state=1;
printf("请输入一个数");
while(state>=1&&state<=8)
{
while(ch!='\n'){
ch=getchar( );
if(ch=='\n'&&(state==3||state==5||state==8))
state=Finish;
switch(state)
{
case 1:
if(ch=='+'||ch=='-') state=2;
else if(isdigit(ch)) state=3;
else state=error;
break;
case 2:
if(isdigit(ch)) state=3;
else state=error;
break;
case 3:
if(isdigit(ch)) ;
else if(ch=='.') state=4;
else if(ch=='E'||ch=='e') state=6;
else state=error;
break;
case 4:
if(isdigit(ch)) state=5;
else state=error;
break;
case 5:
..
case 6:
...
case 7:
...
case 8:
...
}
}

//---------------------------------------------------------------------------

#include <stdio.h>
#include <ctype.h>

int main(void)
{
char c,ch;
int stat;
int point;
int count;
do
{
count=0;
point=0;
stat=1;
while ((c=getchar())!='\n')
{
++count;
if (count==1&&(c=='+'||c=='-')) {
continue;
}
if (!isdigit(c)&&c!='.') {
stat=0;
}
else if (c=='.') {
++point;
}
if (point>1) {
stat=0;
}
if (!stat) {
printf("不是实数\n");
break;
}
}
if (stat) {
printf("是实数\n");
}
fflush(stdin); /*清空输入缓冲区*/
printf("是否继续判断?(y/n)");
ch=getchar();
fflush(stdin);