Force input to be positive numbers only with error handling in C

[亡魂溺海] 提交于 2019-12-12 07:07:39

问题


I have a trivial question to ask. My program should take postive integers only. If there is anything illegal, the user should be prompted to input a number again.

The code I have for now is:

#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);
}

The code above almost did what I want; however, when the input is multiple letters, the output prompts will be print multiple times, which bothers me a lot.

   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: 

I'd appreciate if you can help me fix this or offer better solutions for this seemly trivial problem. Thanks ahead!


回答1:


Use fgets to read a whole line into a buffer. If you only want to process the first character, you can just ignore the rest. Something along the lines of:

char buf[MAX_LINE_LEN];
if (fgets(buf, MAX_LINE_LEN, stdin))
{
    char a = buf[0];
    /* Do handling... */
}
else
{
    /* error */
}

Coded in browser, may contain traces of error.




回答2:


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');
  }
}



回答3:


i have solved your program. Try the following program in 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 choice\n");
        goto GET;
    }
    else
    {
        printf("Wrong choice\n");
        goto GET;
    }
    getch();
}


来源:https://stackoverflow.com/questions/22383449/force-input-to-be-positive-numbers-only-with-error-handling-in-c

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!