C programming - loop until user enters scanf number

I need help checking errors for my program. I am asking the user to enter an integer and I would like to check if the input is an integer. If not, repeat 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;
}

      

+3


source to share


4 answers


scanf

returns the number of elements it read successfully, according to your format. You can set up a loop that only exits when it scanf("%d", &number2);

returns 1

. However, the trick is to ignore invalid data when it 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 are reading multiple times in your code, consider creating a function to hide this loop, and call that function twice in yours main

to avoid duplication.

+7


source


Here is the solution to your problem. I just changed part of your code. Read the comments for any explanation.

#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 worked this out for 2 digit numbers only, but it works fine for more than 2 digit numbers for me. Please let me know that the same is happening in your case. And if you find out why this is happening, please comment.

And you can also use strtol()

instead atoi()

. I don't use it due to the small values.



Difference between atoi()

andstrtol()

atoi()


Pro: Simple.
Pro: convert to int

.
Pro: In the standard C library.
Pro: Fast.
Con: No error handling.
Con: Do not handle either hex or octal.

strtol()


Pro: Simple.
Pro: In the standard C library.
Pro: Good error handling.
Pro: Fast.
Con: Convert to long

, not int

, which may vary in size.

+1


source


I would like to say that you need to do some spot check to check if it reads an scanf

integer or not. I am using fgets

, not interested 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;
}

      

0


source


A clean approach to this problem might be

0


source







All Articles