Why does this code produce 1 on adding characters in C? - c

I was trying to restrict user input from alphabets (Eg: repeat input until correct input is provided ) , in order to get only numbers to be added. Somehow, instead of able to do so, I was able to add alphabets, but with out being '1'
It increments 1 if a number with a character is given.
#include<stdio.h>
int main() {
int x,y;
while(1)
{
printf("Enter a number > ");
if(scanf("%d%d",&x,&y) != 1){
printf("%d",x+y);
break;
}
}
return 0;
}
What could be the reason behind it?

scanf() returns the number of successful conversions it has performed for the input given.
With
scanf("%d%d", &x, &y)
you ask for two integers so scanf() will return 2 if it was successful. Your code however checks for != 1 which will also be true if scanf() returns 0 becuause you entered "a b" and no conversation could be performed.
If not all conversions were successful, all characters not being part of a successful conversion remain in stdin and the next scanf() will try to interpret them again and fail. To prevent that from happening you have to "clear" them:
#include <stdio.h>
int main()
{
while(1)
{
printf("Enter two numbers: ");
int x, y; // define variables as close to where they're used as possible
if (scanf("%d%d", &x, &y) == 2) {
printf("%d\n", x + y);
break;
}
else {
int ch; // discard all characters until EOF or a newline:
while ((ch = getchar()) != EOF && ch != '\n');
}
}
return 0;
}
The more ideomatic way:
int x, y;
while (printf("Enter two numbers: "),
scanf("%d%d", &x, &y) != 2)
{
fputs("Input error :(\n\n", stderr);
int ch;
while ((ch = getchar()) != EOF && ch != '\n');
}
printf("%d\n", x + y);

Related

Do... While creates infinite loop when a variable instead of int is char in c [duplicate]

I've a small C-program which just reads numbers from stdin, one at each loop cycle. If the user inputs some NaN, an error should be printed to the console and the input prompt should return again. On input of "0", the loop should end and the number of given positive/negative values should be printed to the console. Here's the program:
#include <stdio.h>
int main()
{
int number, p = 0, n = 0;
while (1) {
printf("-> ");
if (scanf("%d", &number) == 0) {
printf("Err...\n");
continue;
}
if (number > 0) p++;
else if (number < 0) n++;
else break; /* 0 given */
}
printf("Read %d positive and %d negative numbers\n", p, n);
return 0;
}
My problem is, that on entering some non-number (like "a"), this results in an infinite loop writing "-> Err..." over and over. I guess it's a scanf() issue and I know this function could be replace by a safer one, but this example is for beginners, knowing just about printf/scanf, if-else and loops.
I've already read the answers to the questionscanf() skips every other while loop in C and skimmed through other questions, but nothing really answer this specific problem.
scanf consumes only the input that matches the format string, returning the number of characters consumed. Any character that doesn't match the format string causes it to stop scanning and leaves the invalid character still in the buffer. As others said, you still need to flush the invalid character out of the buffer before you proceed. This is a pretty dirty fix, but it will remove the offending characters from the output.
char c = '0';
if (scanf("%d", &number) == 0) {
printf("Err. . .\n");
do {
c = getchar();
}
while (!isdigit(c));
ungetc(c, stdin);
//consume non-numeric chars from buffer
}
edit: fixed the code to remove all non-numeric chars in one go. Won't print out multiple "Errs" for each non-numeric char anymore.
Here is a pretty good overview of scanf.
scanf() leaves the "a" still in the input buffer for next time. You should probably use getline() to read a line no matter what and then parse it with strtol() or similar instead.
(Yes, getline() is GNU-specific, not POSIX. So what? The question is tagged "gcc" and "linux". getline() is also the only sensible option to read a line of text unless you want to do it all by hand.)
I think you just have to flush the buffer before you continue with the loop. Something like that would probably do the job, although I can't test what I am writing from here:
int c;
while((c = getchar()) != '\n' && c != EOF);
Due to the problems with scanf pointed out by the other answers, you should really consider using another approach. I've always found scanf way too limited for any serious input reading and processing. It's a better idea to just read whole lines in with fgets and then working on them with functions like strtok and strtol (which BTW will correctly parse integers and tell you exactly where the invalid characters begin).
Rather than using scanf() and have to deal with the buffer having invalid character, use fgets() and sscanf().
/* ... */
printf("0 to quit -> ");
fflush(stdout);
while (fgets(buf, sizeof buf, stdin)) {
if (sscanf(buf, "%d", &number) != 1) {
fprintf(stderr, "Err...\n");
} else {
work(number);
}
printf("0 to quit -> ");
fflush(stdout);
}
/* ... */
I had similar problem. I solved by only using scanf.
Input "abc123<Enter>" to see how it works.
#include <stdio.h>
int n, num_ok;
char c;
main() {
while (1) {
printf("Input Number: ");
num_ok = scanf("%d", &n);
if (num_ok != 1) {
scanf("%c", &c);
printf("That wasn't a number: %c\n", c);
} else {
printf("The number is: %d\n", n);
}
}
}
On some platforms (especially Windows and Linux) you can use fflush(stdin);:
#include <stdio.h>
int main(void)
{
int number, p = 0, n = 0;
while (1) {
printf("-> ");
if (scanf("%d", &number) == 0) {
fflush(stdin);
printf("Err...\n");
continue;
}
fflush(stdin);
if (number > 0) p++;
else if (number < 0) n++;
else break; /* 0 given */
}
printf("Read %d positive and %d negative numbers\n", p, n);
return 0;
}
The Solution: You need to add fflush(stdin); when 0 is returned from scanf.
The Reason: It appears to be leaving the input char in the buffer when an error is encountered, so every time scanf is called it just keeps trying to handle the invalid character but never removing it form the buffer. When you call fflush, the input buffer(stdin) will be cleared so the invalid character will no longer be handled repeatably.
You Program Modified: Below is your program modified with the needed change.
#include <stdio.h>
int main()
{
int number, p = 0, n = 0;
while (1) {
printf("-> ");
if (scanf("%d", &number) == 0) {
fflush(stdin);
printf("Err...\n");
continue;
}
if (number > 0) p++;
else if (number < 0) n++;
else break; /* 0 given */
}
printf("Read %d positive and %d negative numbers\n", p, n);
return 0;
}
try using this:
if (scanf("%d", &number) == 0) {
printf("Err...\n");
break;
}
this worked fine for me... try this..
the continue statement is not appropiate as the Err.. should only execute once. so, try break which I tested... this worked fine for you.. i tested....
When a non-number is entered an error occurs and the non-number is still kept in the input buffer. You should skip it. Also even this combination of symbols as for example 1a will be read at first as number 1 I think you should also skip such input.
The program can look the following way.
#include <stdio.h>
#include <ctype.h>
int main(void)
{
int p = 0, n = 0;
while (1)
{
char c;
int number;
int success;
printf("-> ");
success = scanf("%d%c", &number, &c);
if ( success != EOF )
{
success = success == 2 && isspace( ( unsigned char )c );
}
if ( ( success == EOF ) || ( success && number == 0 ) ) break;
if ( !success )
{
scanf("%*[^ \t\n]");
clearerr(stdin);
}
else if ( number > 0 )
{
++p;
}
else if ( number < n )
{
++n;
}
}
printf( "\nRead %d positive and %d negative numbers\n", p, n );
return 0;
}
The program output might look like
-> 1
-> -1
-> 2
-> -2
-> 0a
-> -0a
-> a0
-> -a0
-> 3
-> -3
-> 0
Read 3 positive and 3 negative numbers
I had the same problem, and I found a somewhat hacky solution. I use fgets() to read the input and then feed that to sscanf(). This is not a bad fix for the infinite loop problem, and with a simple for loop I tell C to search for any none numeric character. The code below won't allow inputs like 123abc.
#include <stdio.h>
#include <ctype.h>
#include <string.h>
int main(int argc, const char * argv[]) {
char line[10];
int loop, arrayLength, number, nan;
arrayLength = sizeof(line) / sizeof(char);
do {
nan = 0;
printf("Please enter a number:\n");
fgets(line, arrayLength, stdin);
for(loop = 0; loop < arrayLength; loop++) { // search for any none numeric charcter inisde the line array
if(line[loop] == '\n') { // stop the search if there is a carrage return
break;
}
if((line[0] == '-' || line[0] == '+') && loop == 0) { // Exculude the sign charcters infront of numbers so the program can accept both negative and positive numbers
continue;
}
if(!isdigit(line[loop])) { // if there is a none numeric character then add one to nan and break the loop
nan++;
break;
}
}
} while(nan || strlen(line) == 1); // check if there is any NaN or the user has just hit enter
sscanf(line, "%d", &number);
printf("You enterd number %d\n", number);
return 0;
}
To solve partilly your problem I just add this line after the scanf:
fgetc(stdin); /* to delete '\n' character */
Below, your code with the line:
#include <stdio.h>
int main()
{
int number, p = 0, n = 0;
while (1) {
printf("-> ");
if (scanf("%d", &number) == 0) {
fgetc(stdin); /* to delete '\n' character */
printf("Err...\n");
continue;
}
if (number > 0) p++;
else if (number < 0) n++;
else break; /* 0 given */
}
printf("Read %d positive and %d negative numbers\n", p, n);
return 0;
}
But if you enter more than one character, the program continues one by one character until the "\n".
So I found a solution here: How to limit input length with scanf
You can use this line:
int c;
while ((c = fgetc(stdin)) != '\n' && c != EOF);
// all you need is to clear the buffer!
#include <stdio.h>
int main()
{
int number, p = 0, n = 0;
char clearBuf[256]; //JG:
while (1) {
printf("-> ");
if (scanf("%d", &number) == 0) {
fgets(stdin, 256, clearBuf); //JG:
printf("Err...\n");
continue;
}
if (number > 0) p++;
else if (number < 0) n++;
else break; /* 0 given */
}
printf("Read %d positive and %d negative numbers\n", p, n);
return 0;
}
Flush the input buffer before you scan:
while(getchar() != EOF) continue;
if (scanf("%d", &number) == 0) {
...
I was going to suggest fflush(stdin), but apparently that results in undefined behavior.
In response to your comment, if you'd like the prompt to show up, you have to flush the output buffer. By default, that only happens when you print a newline. Like:
while (1) {
printf("-> ");
fflush(stdout);
while(getchar() != EOF) continue;
if (scanf("%d", &number) == 0) {
...
Hi I know this is an old thread but I just finished a school assignment where I ran into this same problem.
My solution is that I used gets() to pick up what scanf() left behind.
Here is OP code slightly re-written; probably no use to him but perhaps it will help someone else out there.
#include <stdio.h>
int main()
{
int number, p = 0, n = 0;
char unwantedCharacters[40]; //created array to catch unwanted input
unwantedCharacters[0] = 0; //initialzed first byte of array to zero
while (1)
{
printf("-> ");
scanf("%d", &number);
gets(unwantedCharacters); //collect what scanf() wouldn't from the input stream
if (unwantedCharacters[0] == 0) //if unwantedCharacters array is empty (the user's input is valid)
{
if (number > 0) p++;
else if (number < 0) n++;
else break; /* 0 given */
}
else
printf("Err...\n");
}
printf("Read %d positive and %d negative numbers\n", p, n);
return 0;
}
I've recently been through the same problem, and I found a solution that might help a lot of people. The function "scanf" leaves a buffer in memory ... and that's why the infinite loop is caused. So you actually have to "store" this buffer to another variable IF your initial scanf contains the "null" value. Here's what I mean:
#include <stdio.h>
int n;
char c[5];
int main() {
while (1) {
printf("Input Number: ");
if (scanf("%d", &n)==0) { //if you type char scanf gets null value
scanf("%s", &c); //the abovementioned char stored in 'c'
printf("That wasn't a number: %s\n", c);
}
else printf("The number is: %d\n", n);
}
}

How to add the numbers inside the scanf in loop?

Is there some way to add all the numbers in a scanf loop? The loop would stop if the input number is negative. The problem is that the negative must also be included in the sum.
Here, I managed to get the sum of all the positive scanf values repeated in the loop, but the negative number is still not included in the sum of all the numbers.
#include <stdio.h>
main()
{
int z, x;
printf("Enter a number:\n");
z = 0;
scanf("%d", &x);
do
{
z += x;
scanf(" %d", &x);
} while (x >= 0);
printf("Sum = %d ", z);
return 0;
}
A simple rearrangement of the order of statements in your do ... while loop (and removal of the preceding scanf call) will do the trick:
#include<stdio.h>
int main() // You are returning "0" so declare "int" as return type
{
int x = 0, z = 0; // Easier to initialize at the same time as declaration.
printf("Enter a number:\n");
// scanf ("%d", &x); // Don't read here - do that inside the loop.
do {
int test = scanf(" %d", &x); // Read as the FIRST statement in the loop ...
if (test != 1) { // If the "scanf" call failed, we need to clear the input stream ...
int c;
while ((c = getchar()) != '\n' && c != EOF)
; // Clear any offending input
if (c == EOF) break; // Probably can't recover from an EOF, so exit the while loop
}
else z += x; // ... then we can add X even if it's negative
} while (x >= 0); // But end the loop when it IS negative anyway
printf("Sum = %d ", z);
return 0;
}
Note that I have added a test variable to makes sure that the scanf operation succeeded. If the usser enters foo (as mentioned in the comment by William Pursell), then the input buffer is cleared, the addition is skipped, and the read will be attempted again.
I'm not sure if you want to handle an input stream that does not contain a negative value as an error, but you could simply do:
#include <stdio.h>
#include <stdlib.h>
int
main(void)
{
int sum = 0, x, rv;
while( 1 == (rv = scanf ("%d", &x)) ){
sum += x;
if( x < 0 ){
break;
}
}
if( rv == 0 ){
fprintf(stderr, "Invalid input\n");
} else {
printf("Sum = %d\n", sum);
}
return rv == 0 ? EXIT_FAILURE : EXIT_SUCCESS;
}
I think the following behavior is reasonable:
$ echo 4 5 8 5| ./a.out
Sum = 22
$ echo 4 5 -1 5| ./a.out
Sum = 8
$ echo 4 5 not-an-integer 5| ./a.out
Invalid input
Inverting the lines inside the loop should do it:
int z, x;
int ch;
printf("Enter a number:\n");
z = 0;
do
{
if (scanf("%d", &x) == 1) // checking if parsing was successful
{
z += x; // if so, perform the sum
}
else
{
puts("Bad input"); // if user inputs a bad value
while((ch = getchar()) != '\n' && ch != EOF){} // you clear the input buffer
}
} while (x >= 0);
printf("Sum = %d ", z);
Note that I also removed the first scanf ouside the loop, which becomes unneeded.

Scanf returns 0 without waiting for input

I have never programmed in C and today I have to write small code. Program is very easy - I want to add two integers.
But when I'm trying to check if given input is a number and first scanf returns 0, the second one returns 0 too without waiting for input.
Code:
int main()
{
int a = 0;
int b = 0;
printf("Number a:\n");
if (scanf("%d", &a) != 1)
{
printf("Not a number. a=0!\n");
a = 0;
}
printf("Number b:\n");
if (scanf("%d", &b) != 1)
{
printf("Not a number. b=0!\n");
b = 0;
}
printf("%d\n", a+b);
return 0;
}
The input that failed to convert to a number for the first fscanf() is still pending in standard input's buffer and causes the second fscanf() to fail as well. Try discarding offending input and re-prompting the user:
#include <stdio.h>
int main(void) {
int a = 0;
int b = 0;
int c;
printf("Number a:\n");
while (scanf("%d", &a) != 1) {
printf("Not a number, try again:\n");
while ((c = getchar()) != EOF && c != '\n')
continue;
if (c == EOF)
exit(1);
}
printf("Number b:\n");
while (scanf("%d", &b) != 1) {
printf("Not a number, try again:\n");
while ((c = getchar()) != EOF && c != '\n')
continue;
if (c == EOF)
exit(1);
}
printf("%d\n", a + b);
return 0;
}
Factorizing the code with a utility function makes it much clearer:
#include <stdio.h>
int get_number(const char *prompt, int *valp) {
printf("%s:\n", prompt);
while (scanf("%d", valp) != 1) {
printf("Not a number, try again:\n");
while ((c = getchar()) != EOF && c != '\n')
continue;
if (c == EOF)
return 0;
}
return 1;
}
int main(void) {
int a, b;
if (!get_number("Number a", &a) || !get_number("Number b", &b)) {
return 1;
}
printf("%d\n", a + b);
return 0;
}
That is because, once the first scanf() failed, it is probably because of matching failure, and the input which caused the matching failure, remains inside the input buffer, waiting to be consumed by next call.
Thus, the next call to scanf() also try to consume the same invalid input residing in the input buffer immediately, without waiting for the explicit external user input as the input buffer is not empty.
Solution: After the first input fails for scanf(), you have to clean up the input buffer, for a trivial example, something like while (getchar() != '\n'); should do the job.
This happens if there is any input from the previous entry, can take that, and skip input from the user. In the next scanf also It takes the new line which is left from the last scanf statement and automatically consumes it. That's what happening in your code.
You can clear previous input in stdin stream by using fflush(stdin); before starting your program.
This can also be solved by leaving a space before % i.e scanf(" %d",&n);,Here leaving whitespace ensures that the previous new line is ignored.
Or we can use getc(stdin) before calling any scanf statement, Sometimes it helps very much.
int main()
{
int a = 0;
int b = 0;
printf("Number a:");
//getc(stdin);
if (scanf(" %d", &a) != 1)
{
printf("Not a number. a=0!\n");
a = 0;
}
printf("Number b:\n");
//getc(stdin);
if (scanf(" %d", &b) != 1)
{
printf("Not a number. b=0!\n");
b = 0;
}
printf("%d\n", a+b);
return 0;
}
It's because of input and output aren't synchronized in C. The program can output some lines after user's input while the input hasn't been read. Try to run this code:
char token;
scanf("%c", &token);
printf("%c\n", token);
printf("line 1\n");
scanf("%c", &token);
printf("%c\n", token);
printf("line 2\n");
scanf("%c", &token);
printf("%c\n", token);
printf("line 3\n");
And input abc in one line.
You can imagine this like there are two separated consoles, one for input and another for output.
For example you want to input asd for a and 3 for b. In this case, the first scanf won't find any number and will return 0. But it also won't read anything from the input. Because of this, the second scanf will see asd too.
To clear the input if a isn't a number, you should input all remaining chars in the line until '\n' (look at the #Sourav's solution)
You could do the same thing using strings without problems with scanf. Just take the user input as string and convert it to integer. Then convert the string back to integer to check whether they are the same. If they are the same, treat a and b as integers, if not, do what you do (You will need to include string.h). Here is the working code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int a;
int b;
char str1[100];
char str2[100];
printf("Number a:\n");
scanf("%s", &str1); //take input as a string
a = atoi(str1); //convert string to integer
snprintf(str2, 100, "%d", a); //convert integer back to string
//if the integer converted to string is not the same as the string converted to integer
if (strcmp(str1, str2)!= 0)
{
printf("Not a number. a=0!\n");
a = 0;
}
printf("Number b:\n");
scanf("%s", &str1);
b = atoi(str1);
snprintf(str2, 100, "%d", b);
if (strcmp(str1, str2)!= 0)
{
printf("Not a number. b=0!\n");
b = 0;
}
printf("%d\n", a+b);
return(0);
}

for-loop stuck in endless loop [duplicate]

I have never programmed in C and today I have to write small code. Program is very easy - I want to add two integers.
But when I'm trying to check if given input is a number and first scanf returns 0, the second one returns 0 too without waiting for input.
Code:
int main()
{
int a = 0;
int b = 0;
printf("Number a:\n");
if (scanf("%d", &a) != 1)
{
printf("Not a number. a=0!\n");
a = 0;
}
printf("Number b:\n");
if (scanf("%d", &b) != 1)
{
printf("Not a number. b=0!\n");
b = 0;
}
printf("%d\n", a+b);
return 0;
}
The input that failed to convert to a number for the first fscanf() is still pending in standard input's buffer and causes the second fscanf() to fail as well. Try discarding offending input and re-prompting the user:
#include <stdio.h>
int main(void) {
int a = 0;
int b = 0;
int c;
printf("Number a:\n");
while (scanf("%d", &a) != 1) {
printf("Not a number, try again:\n");
while ((c = getchar()) != EOF && c != '\n')
continue;
if (c == EOF)
exit(1);
}
printf("Number b:\n");
while (scanf("%d", &b) != 1) {
printf("Not a number, try again:\n");
while ((c = getchar()) != EOF && c != '\n')
continue;
if (c == EOF)
exit(1);
}
printf("%d\n", a + b);
return 0;
}
Factorizing the code with a utility function makes it much clearer:
#include <stdio.h>
int get_number(const char *prompt, int *valp) {
printf("%s:\n", prompt);
while (scanf("%d", valp) != 1) {
printf("Not a number, try again:\n");
while ((c = getchar()) != EOF && c != '\n')
continue;
if (c == EOF)
return 0;
}
return 1;
}
int main(void) {
int a, b;
if (!get_number("Number a", &a) || !get_number("Number b", &b)) {
return 1;
}
printf("%d\n", a + b);
return 0;
}
That is because, once the first scanf() failed, it is probably because of matching failure, and the input which caused the matching failure, remains inside the input buffer, waiting to be consumed by next call.
Thus, the next call to scanf() also try to consume the same invalid input residing in the input buffer immediately, without waiting for the explicit external user input as the input buffer is not empty.
Solution: After the first input fails for scanf(), you have to clean up the input buffer, for a trivial example, something like while (getchar() != '\n'); should do the job.
This happens if there is any input from the previous entry, can take that, and skip input from the user. In the next scanf also It takes the new line which is left from the last scanf statement and automatically consumes it. That's what happening in your code.
You can clear previous input in stdin stream by using fflush(stdin); before starting your program.
This can also be solved by leaving a space before % i.e scanf(" %d",&n);,Here leaving whitespace ensures that the previous new line is ignored.
Or we can use getc(stdin) before calling any scanf statement, Sometimes it helps very much.
int main()
{
int a = 0;
int b = 0;
printf("Number a:");
//getc(stdin);
if (scanf(" %d", &a) != 1)
{
printf("Not a number. a=0!\n");
a = 0;
}
printf("Number b:\n");
//getc(stdin);
if (scanf(" %d", &b) != 1)
{
printf("Not a number. b=0!\n");
b = 0;
}
printf("%d\n", a+b);
return 0;
}
It's because of input and output aren't synchronized in C. The program can output some lines after user's input while the input hasn't been read. Try to run this code:
char token;
scanf("%c", &token);
printf("%c\n", token);
printf("line 1\n");
scanf("%c", &token);
printf("%c\n", token);
printf("line 2\n");
scanf("%c", &token);
printf("%c\n", token);
printf("line 3\n");
And input abc in one line.
You can imagine this like there are two separated consoles, one for input and another for output.
For example you want to input asd for a and 3 for b. In this case, the first scanf won't find any number and will return 0. But it also won't read anything from the input. Because of this, the second scanf will see asd too.
To clear the input if a isn't a number, you should input all remaining chars in the line until '\n' (look at the #Sourav's solution)
You could do the same thing using strings without problems with scanf. Just take the user input as string and convert it to integer. Then convert the string back to integer to check whether they are the same. If they are the same, treat a and b as integers, if not, do what you do (You will need to include string.h). Here is the working code:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main()
{
int a;
int b;
char str1[100];
char str2[100];
printf("Number a:\n");
scanf("%s", &str1); //take input as a string
a = atoi(str1); //convert string to integer
snprintf(str2, 100, "%d", a); //convert integer back to string
//if the integer converted to string is not the same as the string converted to integer
if (strcmp(str1, str2)!= 0)
{
printf("Not a number. a=0!\n");
a = 0;
}
printf("Number b:\n");
scanf("%s", &str1);
b = atoi(str1);
snprintf(str2, 100, "%d", b);
if (strcmp(str1, str2)!= 0)
{
printf("Not a number. b=0!\n");
b = 0;
}
printf("%d\n", a+b);
return(0);
}

How to prevent non-numeric input in C?

I wrote a small C program which will get an input from the user and check if the input is even or odd.
#include<stdio.h>
int main()
{
int n;
printf("Enter an integer number: ");
scanf("%d",&n);
if(n%2 == 0)
{
printf("\n%d is an EVEN number.\n",n);
}
else
printf("\n%d is an ODD number.\n",n);
return 0;
}
but when I enter an alphabet or a symbol, it shows the output as 0 and says input is EVEN. How can I prevent user from entering alphabets and symbols? What's the easiest way to do that?
You have to check the return value of scanf. From the documentation:
Return Value
Number of receiving arguments successfully assigned, or EOF if read failure occurs before the first receiving argument was assigned.
Applied to your code:
#include <stdio.h>
#include <stdlib.h>
int
main()
{
int n;
printf("Enter an integer number: ");
if (scanf("%d", &n) != 1)
{
printf("This is not a number.\n");
return EXIT_FAILURE;
}
else if (n % 2 == 0)
{
printf("\n%d is an EVEN number.\n", n);
return EXIT_SUCCESS;
}
else
{
printf("\n%d is an ODD number.\n", n);
return EXIT_SUCCESS;
}
}
Simply check the return value of scanf - it'll tell you how many format objects were successfully parsed. In this case, it'll return 1 if it could parse an int, and 0 if it couldn't.
If the input is an integer, then scanf() will return 1 so you can check
if (scanf("%d", &integer) != 1)
invalidInput();
to ask the user again you should know that there could be characters left in the stdin that need to be read so you can flush them with getchar() so a complete function would be
int scanint(const char *const message)
{
int value;
printf("%s > ", message);
while (scanf("%d", &value) != 1)
{
int chr;
printf("\tinvalid input...\n");
do {
chr = getchar();
} while ((chr != EOF) && (chr != '\n'));
printf("%s > ", message);
}
return value;
}
and you can use it like this
int main()
{
int value = scanint("please input an integer");
printf("your input was: %d\n", value);
return 0;
}
I can give you two approaches:
very easy — check for return value of scanf(). 1 indicates success (integer read) and 0 if any non-integer is put in there (or EOF on EOF).
by writing code for it:
#include <ctype.h>
#include <stdlib.h>
int isNumeric (const char * s)
{
if (s == NULL || *s == '\0' || isspace(*s))
return 0;
char * p;
strtod (s, &p);
return *p == '\0';
}
Now in this case your scanf has to take a string from user and then pass that string to the function isNumeric().

Resources