I'm trying to run a simple C program on my Mac. It worked fine for a while but then suddenly scanf stopped working. I basically want to read in an integer value and output what was entered. No matter the integer I enter the program keeps outputting 0. I've tried the suggestions here but nothing works. I've tried running the program in both terminal and xcode but still nothing. Any ideas?
#include <stdio.h>
int main(){
int numberOfElements = 0;
scanf("Number of elements: %d",&numberOfElements);
printf("%d\n",numberOfElements); //keeps returning 0 no matter the number I enter
return 0;
}
When you include any non-format characters into scanf/fscanf/sscanf
format string, it means that you require these characters to be present in the input stream (or input string, in case of sscanf
). If these characters are not present in the input, scanf
fails. Space character has special meaning though, causing scanf
to skip all whitespace, but not requiring any whitespace to be present.
So, in order for this scanf
to succeed
scanf("Number of elements: %d", &numberOfElements);
you have to enter, literally
Number of elements: 10
or
Numberof elements:10
or
Numberofelements: 10
or something like that. I.e. you have to type in the words Number
, of
, elements
and the :
as well. If you just enter 10
, the scanf
will fail, since a mere 10
does not match the requested format.
I'm sure this was not your intent. What you really wanted to do, apparently, is to print the prompt using printf
and then do a simple
scanf("%d", &numberOfElements);
The aforementioned feature of scanf
could be useful, but probably only in some rare cases. This means that when you see any non-format text in scanf
format string, there's a good possibility that something is wrong.
You have to print the prompt, and only scan the input:
printf("Number of elements: ");
fflush(stdout);
scanf("%d", &numberOfElements);
Generally, it is better to avoid using scanf()
directly. Instead, you can obtain a line of input and then use sscanf()
on the retrieved string for better control of errors.
char line[MAX_LINE];
if (fgets(line, sizeof(line), stdin) != NULL) {
if (sscanf(line, "%d", &numberOfElements) != 1) {
printf("You didn't input a number: %s", line);
/* ... */
}
}
You should not have Number of elements:
in the scanf
statement. You want to change the scanf
statement to:
printf ( "Number of elements: " );
scanf ("%d", &numberOfElements );