Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why won't the second scanf() execute

Tags:

c

scanf

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?

like image 948
Nathu Avatar asked Feb 23 '17 05:02

Nathu


2 Answers

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);
}
like image 188
Peter G Avatar answered Oct 16 '22 00:10

Peter G


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.

like image 38
msc Avatar answered Oct 15 '22 22:10

msc