Error: ignoring scanf return value?
I only have a few days to program in C, so I'm not really sure what happened to this code:
#include <stdio.h>
int main(int argc, char * argv[]) {
int sides;
printf("Please enter length of three sides :\n");
scanf("%d", &sides);
return 0;
}
The error message I am getting looks like this:
ignore scanf return value
What am I doing wrong here and what can I do to fix it?
source to share
This is a warning that prevents your compiler from performing the task (settings too strict). Check the return value of scanf () for errors and the warning should go away.
Return value
On success, the function returns the number of elements read successfully. This count may correspond to the expected number of readings or less, even zero if a corresponding failure occurs. in case of input failure, before any data can be read successfully, EOF is returned.
source to share
You can code
if (scanf("%d", &sides) >0) {
printf("you want %d sides.\n", sides);
}
else printf("You did not enter any number.\n");
The scanf function (please go to the link) has multiple roles
- it expects input and can modify the variables you passed to the address.
- it returns the number of successfully entered elements
source to share
scanf
returns the number of "elements" that is, the values passed in the format string (eg %d
, %c
etc.) and in the arguments for scanf
, for example, to read two integers separated by a comma and a space, you would use:
int x, y;
int items = scanf("%d, %d", &x, &y);
assert(items == 2);
I already messed up what my suggestion would be above - instead of adding unused variables, if you just want to read it, add a statement:
#include <assert.h>
/* ... */
assert(scanf("%d", &sides) > 0);
/* ... */
Unfortunately assert(scanf("%d", &sides));
not enough due to EOF (this will return -1
). It would be really elegant.
I think this is the right way to go if you don't want to continue your program with an uninitialized variable ( sides
) in this case.
Alternatively, you can the scanf
result scanf
into a variable and handle it gracefully like in other answers.
source to share