C programming - Loop until user inputs number scan

2019-01-19 07:27发布

问题:

I need help with error checking for my program. I'm asking the user to input a integer and I would like to check if the users input is a integer. If not, repeat the scanf.

My code:

int main(void){

  int number1, number2;
  int sum;

  //asks user for integers to add
  printf("Please enter the first integer to add.");
  scanf("%d",&number1);

  printf("Please enter the second integer to add.");
  scanf("%d",&number2);
  //adds integers
  sum = number1 + number2;

  //prints sum
  printf("Sum of %d and %d = %d \n",number1, number2, sum);

  //checks if sum is divisable by 3
  if(sum%3 == 0){
    printf("The sum of these two integers is a multiple of 3!\n");
  }else {
    printf("The sum of these two integers is not a multiple of 3...\n");
  }
  return 0;
}

回答1:

scanf returns the count of items that it has successfully read according to your format. You can set up a loop that exits only when scanf("%d", &number2); returns 1. The trick, however, is to ignore invalid data when scanf returns zero, so the code would look like this:

while (scanf("%d",&number2) != 1) {
    // Tell the user that the entry was invalid
    printf("You did not enter a valid number\n");
    // Asterisk * tells scanf to read and ignore the value
    scanf("%*s");
}

Since you read a number more than once in your code, consider making a function to hide this loop, and call this function twice in your main to avoid duplication.



回答2:

Here is a solution of your problem. I just modified some of your code. Read comments for any explanations.

#include<stdio.h>

#include<stdlib.h>      //included to use atoi()
#include<ctype.h>       //included to use isalpha()

#define LEN 3   //for two digit numbers

int main(void)
{

    char *num1=malloc(LEN);
    char *num2=malloc(LEN);
    int i,flag=0;

    int number1,number2;
    int sum;

    do
    {
        printf("Please enter the first integer to add = ");
        scanf("%s",num1);
        for (i=0; i<LEN; i++)   //check for every letter of num1
        {
            if (isalpha(num1[i]))   //isalpha(num1[i]) returns true if num1[i] is alphabet
            {                       //isalpha() is defined in ctype.h
                flag=1;             //set flag to 1 if num1[i] is a alphabet
            }
        }
        if(flag)
        {
            printf("Not a valid Integer\n");
            flag=0;
            continue;
        }
        else
        {
            break;
        }
    } while(1);

    do
    {
        printf("Please enter the second integer to add = ");
        scanf("%s",num2);
        for (i=0; i<LEN; i++)
        {
            if (isalpha(num2[i]))
            {
                flag=1;
            }
        }
        if(flag)
        {
            printf("Not a valid Integer\n");
            flag=0;
            continue;
        }
        else
        {
            break;
        }
    } while(1);

    //strings to integers
    number1= atoi(num1);    //atoi() is defined in stdlib.h
    number2= atoi(num2);

    //adds integers
    sum = number1 + number2;

    //prints sum
    printf("Sum of %d and %d = %d \n",number1, number2, sum);

    //checks if sum is divisable by 3
    if(sum%3 == 0)
    {
        printf("The sum of these two integers is a multiple of 3!\n");
    }
    else
    {
        printf("The sum of these two integers is not a multiple of 3...\n");
    }
    return 0;
}

I designed this for only two digit numbers, but it is working fine for more than two digit numbers for me. Please let me know that same is happening in your case.
And if you will find why this is happening please comment.

And you can also use strtol() instead of atoi(). I am not using it because of small values.

Difference between atoi() and strtol()

atoi()
Pro: Simple.
Pro: Convert to an int.
Pro: In the C standard library.
Pro: Fast.
Con: No error handling.
Con: Handle neither hexadecimal nor octal.

strtol()
Pro: Simple.
Pro: In the C standard library.
Pro: Good error handling.
Pro: Fast.
Con: Convert to a long, not int which may differ in size.



回答3:

I would like to say that you have to make some custom validation to check if whether scanf read integer or not.I am used fgets not interested in scanf.

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

int validate ( char *a )
{
  unsigned x;
  for ( x = 0; x < strlen ( a ); x++ )
    if ( !isdigit ( a[x] ) ) return 1;
  return 0;
}

int main ( void )
{
  int i;
  char buffer[BUFSIZ];
  printf ( "Enter a number: " );
  if ( fgets ( buffer, sizeof buffer, stdin ) != NULL ) {
    buffer[strlen ( buffer ) - 1] = '\0';
    if ( validate ( buffer ) == 0 ) {
      i = atoi ( buffer );
      printf ( "%d\n", i );
    }
    else
      printf ( "Error: Input validation\n" );
  }
  else
    printf ( "Error reading input\n" );
  return 0;
}


回答4:

A clean approach to this problem can be

  1. read from stdin using fgets().

  2. use strtol() to convert and store the value into an int. Then check for the char **endptr to determine whether the conversion is success [indicates integer] or not.

  3. Perform remaining task.