1

my program adds numbers entered by the user. It runs and works great until a character is entered instead of an integer. Is there a simple way to make sure only integers are entered from the keyboard?

Here is my code.

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

int main(int argc, char **argv)
{
   int n, sum = 0, i, TotalOfNumbers;

   printf("Enter the number of integers you want to add\n"); 
   scanf("%d", &n); 

   printf("Enter %d integers\n",n); 

   for (i = 1; i <= n; i++)
   {
      scanf("%d",&TotalOfNumbers);
      sum = sum + TotalOfNumbers;
   }

   printf("Sum of entered integers = %d\n",sum); 

   return 0;
}
Borgleader
  • 15,826
  • 5
  • 46
  • 62
Derk
  • 29
  • 1
  • 11

3 Answers3

2

You need to check the return value of scanf. If the input was a valid number, it will return 1. If the input was not a valid number, it will return something else. Here is your code modified to put the checks in.

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

int get_number()
{
   int num;
   int ret;

   ret = scanf("%d", &num);

   if (ret != 1) {
      printf("bad number\n");
      exit(EXIT_FAILURE);
   }

   return num;
}

int main(int argc, char **argv)
{
   int n, sum = 0, i, TotalOfNumbers;

   printf("Enter the number of integers you want to add\n"); 
   n = get_number();

   printf("Enter %d integers\n",n); 

   for (i = 1; i <= n; i++)
   {
      TotalOfNumbers = get_number();
      sum = sum + TotalOfNumbers;
   }

   printf("Sum of entered integers = %d\n",sum); 

   return 0;
}
Zhehao Mao
  • 1,789
  • 13
  • 13
1

Check the ferror state on the input stream

scanf("%d",&TotalOfNumbers);
if(!ferror(stdin)){
  sum = sum + TotalOfNumbers;
}
Joatin
  • 106
  • 3
1

In addition to posted answer, there options not general as posted, but quicker. First if you want to skip some final set of characters.In following example all letters,! and + will be skiped

int n;
scanf("%*[a-zA-Z!+]%d",&n);
printf("\n%d",n);

for input

 weweqewqQQWWW!!!!+++3332

the output is

 3332

Next option is to use buffer wich allowed to read everything untill number is met, and then read the number. The disadvantage is that buffer size is limited

char buf[25];
int n;

scanf("%[^0-9]%d",buf,&n);
printf("\n%d",n);

For input

fgfuf@$@^^@^@@4565

Output

4565
Dabo
  • 2,371
  • 2
  • 18
  • 26