I'm trying to execute this block of code.
#include <stdio.h>
int main(void)
{
printf("Start from here\n");
int e, f, g, h;
scanf("%d,%d", &e, &f);
scanf("%d, %d", &g, &h);
printf("%d %d %d %d", e, f, g, h);
}
When I input 2,0
or something that matches the format string in the first scanf()
, the second scanf()
also executes.
However, if I input something like 2-0
in the first scanf()
, the program skips the second scanf()
and goes straight to the printf()
For example, here's the input and output of a sample run of the program. The second line is the input.
Start from here
1-2
1 0 -2 -856016624u
Notice how the program completely skipped the second scanf()
, and went straight to the printf()
. Why is the second scanf()
being skipped over here?
scanf
's format string cares about the non-format specifiers in it too. When you write "1-2" the first scanf will read "1", then look for a comma. It won't find one, so it'll give up. Now, the second scanf will see "-2" and then look for a comma. It won't find one, so it'll give up.
The end result is that the other two variables won't get set so they end up being whatever garbage is in their memory location at execution time.
You can avoid this by checking the return value of scanf. It'll tell you how many values it found. Try this:
#include <stdio.h>
int main(void)
{
printf("Start from here\n");
int e, f, g, h;
if (scanf("%d,%d", &e, &f) != 2) { /* error handling */ }
if (scanf("%d, %d", &g, &h) != 2) { /* error handling */ }
printf("%d %d %d %d", e, f, g, h);
}
Remove a comma between the two format specifier.
scanf("%d %d", &e, &f); // Remove comma in first argument of scanf
scanf("%d %d", &g, &h); // Remove comma in first argument of scanf
^^^
Remove comma between two numbers
Because scanf
will only skip white space and the comma
is not white space.
What actually happens when you ask scanf
to read numeric data is that it first skips any white space it finds and then it reads characters until the character it reads cannot form part of a number.
In this case, when it encounters the comma, it stops reading. Since it has not read any digits, there is no number for it to store, so it simply leaves the original value.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With