Reputation: 23
I am trying to create program which checks if input from user is a number. This works fine for all of the number and charatcers entered, except for numbers in range of 48 to 57. I've been looking through StackOverflow forum and could not find the answer. Could you please advise, what I am doing wrong?
Here is my code:
#include<stdio.h>
#include<stdlib.h>
#include<ctype.h>
int main(){
int tab[100];
int input;
int index = 0,count=0;
printf("Podaj liczby:\n");
do{
scanf("%i", &input);
if(!isdigit(input)){
if(input!=0){
tab[index] = (int)input;
index++;
}
}else{
printf("Incorrect input");
return 1;
}
}while(input!=0 && index<100);
if(index<2){
printf("not enough data available");
return 2;
}
for(int i = 0; i <index; i++){
count = 0;
for(int j = i+1;j< index; j++){
if((tab[i] == tab[j]) && tab[i]!=0) {
count++;
tab[j] = 0;
}
}
if(count>0){
printf("%i ",tab[i]);
}
}
return 0;
}
Upvotes: 0
Views: 389
Reputation: 61984
The if(!isdigit(input))
clause is checking whether input
is a digit, and it jumps to the else
part if it is. So, if this was ever going to work, you would have to get rid of the '!' operator.
Which leaves us with the next problem: you are using scanf()
to read int
s. There is no more checking to be done to see whether an int
is a number. An int
is already a number.
But what you do, is that you treat the int
as a char
and pass it to isdigit()
, which will of course only succeed if the char
is between 0
and 9
, which corresponds to int
numbers between 48
and 57
. So, only these numbers succeed, and then you negate the result of isdigit()
, so you think that only these numbers fail.
Long story short: quit checking whether your numbers are numbers, they are already numbers.
Upvotes: 0
Reputation: 107759
scanf("%i", &input);
scanf
with the format %i
converts its input to an integer. If the user presses 4 2 Enter, that makes the scanf
call equivalent to input = 42
.
If the input can't be converted to an integer, scanf
returns EOF
and doesn't set input
. Since you don't check the return value of scanf
, your program continues with an indeterminate value in input
. (In theory that's undefined behavior, but in practice your program will run with whatever happened to be in the memory location of input
.)
if(!isdigit(input)){
This tests whether the number input
is the numerical code of a digit character. In practice, the correspondence between characters and their numerical codes on your computer is ASCII, so digits occupy the range from 48 to 57 inclusive. So the body of this if
clause only runs if input
is not between 48 and 57.
I have no idea why you'd do that. If you meant to check whether the input is valid, check the return value of scanf
. If you thought you were checking the first character of the input, then 1. no you aren't, you're checking the result of the conversion, you can't access the raw input from the user; and 2. you'd only be checking one character anyway so your check couldn't possibly be correct.
Upvotes: 3