我有一个微不足道的问题要问。我的程序应该只接受正整数。如果有非法内容,应提示用户重新输入号码。
我现在的代码是:
#include<stdio.h>
int main(){
int reads;
int num=0;
char a;
while(num<=0){
printf("Please Enter positive integer: ");
while(((reads = scanf("%d%c", &num, &a)) != 2 && reads != EOF) || a != 'n' ){
do {
printf("Please Enter positive integer: ");
reads = scanf("%c", &a);
}while(reads != EOF && a != 'n');
}
}
printf("Num is: %d", num);
}
上面的代码几乎完成了我想要的;但是,当输入是多个字母时,输出提示将被打印多次,这让我很困扰。
Please Enter positive integer: pdesf
Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: dfwerasdfwe
Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only: Enter positive numbers only:
如果你能帮我解决这个问题,或者为这个看似微不足道的问题提供更好的解决方案,我将不胜感激。谢谢吧! 使用fgets
将整行读入缓冲区。如果您只想处理第一个字符,则可以忽略其余字符。类似以下语句:
char buf[MAX_LINE_LEN];
if (fgets(buf, MAX_LINE_LEN, stdin))
{
char a = buf[0];
/* Do handling... */
}
else
{
/* error */
}
在浏览器中编码,可能包含错误痕迹
while(num<=0){
printf("Please Enter positive integer: ");
while(((reads = scanf("%d%c", &num, &a)) != 2 && reads != EOF) || a != 'n' ){
printf("Please Enter positive integer: ");
while(getchar() != 'n');
}
}
我已经解决了你的程序。在Turbo c++中试试下面的程序:
#include<stdio.h>
#include<conio.h>
main()
{
char n[2],ni;
clrscr();
GET:
printf("Enter positive number: ");
scanf("%s",&n);
if(atoi(n)>0)
{
printf("You have entered ");
ni=atoi(n);
printf("%d",ni);
}
else if(atoi(n)<=0)
{
printf("Wrong choicen");
goto GET;
}
else
{
printf("Wrong choicen");
goto GET;
}
getch();
}