Reputation: 17
I want to create a program that says if a number is odd or even, but if I type a letter, the program must stop. What I want to do is to create an if-statement that allows the program to understand if what I typed is a number or something else. This is the code.
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
int a,b;
printf("type a number ");
scanf("%d", &a);
printf("\n");
if (a<0) //This is supposed to understand if what I typed is a number, but it's not correct at all.
{
printf("ERROR, YOU MUST TYPE A NUMBER, NOT LETTERS.");
system("PAUSE \n");
return 0;
}
b=(a%2);
if (b != 0)
{
printf("it's an odd number! ");
printf("\n\n");
system("PAUSE");
return 0;
}
else
{
printf("it's an even number! ");
printf("\n\n");
system("PAUSE");
return 0;
}
}
Upvotes: 0
Views: 349
Reputation: 93476
scanf()
returns the number of format specifiers that match, so will return zero if the text entered cannot be interpreted as a decimal integer.
printf("type a number ");
int converted = scanf("%d", &a);
printf("\n");
if( converted == 0)
{
printf("ERROR, YOU MUST TYPE A NUMBER, NOT LETTERS.");
system("PAUSE \n");
return 0;
}
Testing for less that zero will not work since -1 for example is a perfectly valid decimal integer. Had you initialised a
to -1, it might have appeared to work, but you could not then enter a negative number. That said scanf()
does not guarantee not to modify the arguments on failure ot match.
Upvotes: 2
Reputation: 4084
You could read into a character buffer using format, say, %40s (assuming you buffer is 40 characters), then use strtol() to see if the token was an integer without extra junk at the end.
Upvotes: 0
Reputation: 26315
Checking if a<0
does not work in this case, as scanf()
either returns 0 if no integer was found, or the number of integers found. Another case is that EOF is returned if the input is reached before any conversion is occuers. Just check if scanf()
read one integer successfully:
if (scanf("%d", &a) != 1) {
printf("Invalid number\n");
exit(EXIT_FAILURE);
}
/* else, valid integer was found */
/* other code */
You can also just use fgets(3)
to read the input string, and strtol(3)
for more thorough integer conversion. Here is an example:
char number[50];
char *endptr;
int num;
size_t slen;
if (fgets(number, 50, stdin) != NULL) {
/* removes newline appended from fgets() */
slen = strlen(input);
if (slen > 0 && number[slen-1] == '\n') {
number[slen-1] = '\0';
}
num = strtol(number, &endptr, 10);
if (endptr == number) {
/* No digits found */
}
if (*endptr != '\0') {
/* more characters found after number */
}
/* more error checking at man page */
}
Upvotes: 1