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

前端 未结 3 1179
广开言路
广开言路 2020-12-22 05:19

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.

Th

相关标签:
3条回答
  • 2020-12-22 05:57

    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();
    }
    
    0 讨论(0)
  • 2020-12-22 06:12

    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.

    0 讨论(0)
  • 2020-12-22 06:13
    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');
      }
    }
    
    0 讨论(0)
提交回复
热议问题