tags:

views:

26

answers:

2

I want to use the following code just to check the input.

#include <stdio.h>
#include <iostream>
#include <ctype.h>

int main() 
  {
    int number1; 

    puts("Enter number 1 please:");
    scanf_s("%d",&number1);

    if (isdigit(number1)) 
    {
      puts("Input is correct.");

    }
    else 
    {
      puts("Your input is not correct. Enter a number please.");
    }

      std::cin.get();
      std::cin.get();


  }

Unfortunately it doensn't work. I type in a digit and my response is "Your input is not...". Any suggestions where the problem is?

A: 

Your problem is in the use of isdigit. Compare this code:

int main() 
{
int number1; 

puts("Enter number 1 please:");
scanf_s("%d",&number1);
printf("You entered %d\n", number1);
if (isdigit(number1)) 
{
  puts("Input is correct.");

}
else 
{
  puts("Your input is not correct. Enter a number please.");
}

  std::cin.get();
  std::cin.get();


}

When you enter a valid number, this is reflected in the successful printf of this number.

You should check the return of scanf, not use isdigit, such as this sample code:

int main() 
{
int number1; 

puts("Enter number 1 please:");
if (scanf_s("%d",&number1))        
  puts("Input is correct.");
else
  puts("Your input is not correct. Enter a number please.");

std::cin.get();
std::cin.get();
}

I believe that for more than one field, you will need to check the return value of scanf more closely than simply zero or one.

DeadMG
Thanks. Your solution is definetly smarter than mine.
Ordo
A: 

isdigit accepts number1 of type char and not int. Replacing number1 to be of type char will solve the problem and report correct results.

rpoplai
Sorry but it doesn't work. I changed int number1 in char number1, but i still have the same problem.
Ordo
You also need to change %d and make it to %c
rpoplai