find the error in the program ?

0 votes
asked Sep 4 by anonymous

Program run in the codeblock but ouput not print find the error


main()
{
int x=0;
x=getIntegerOnly();
printf("enter values are %d",x);
getch();
}
int getIntegerOnly()
{
int num=0,ch;
do{
ch=getch();
if(ch>=48&&ch<=57)
{
        printf("%c",ch);
num=num*10+(ch-48);
}
if(ch==13)
break;
}while(1);
return(num);
}

1 Answer

0 votes
answered 3 days ago by (220 points)
I would recommend using literals instead of char ordinal values, for instance, instead of (ch>=48&&ch<=57), you can use ( ch >= '0' && ch <= '9' ), the value remains the same, but it is easier to read the code and you won't get lost in it.

And lastly, I assume that if you get ch == 13 then you want to return(num), for that you are using "do {} while(1)" loop, but I don't understand why, you can just set it as "while (ch != 13) {}", in that scenario you won't have to break out of the cycle and be sure your number is returned.
Welcome to OnlineGDB Q&A, where you can ask questions related to programming and OnlineGDB IDE and and receive answers from other members of the community.
...