cscanf

Putting text in scanf makes the code output random numbers?


I am learning C in my computing class and we were introduced to scanf today. This is the line of code that was used to introduce scanf:

#include <stdio.h>
void main() 
{
float x,y;
scanf("%f %f",&x,&y);
printf("%2f\n",x+y);
}

This works fine, if you put in two numbers it'll print the sum. I thought it might work like pythons input function and so i modified the above code to include some text in scanf as follows:

#include <stdio.h>
void main() 
{
float x,y;

scanf("insert no  in format x y %f %f",&x,&y);

printf("%2f\n",x+y);
}

The output I get is not 10, but some random number. I say random as I tried to run the code multiple times, each time I received a different output.

Is this something to do with memory allocation? Can scanf just not strings?


Solution

  • scanfis for reading input, not printing output. If you put text in there, it tries to match that text. If it can't match that text (you'd have to input that exact text), the function fails and it is undefined behavior if you try to use those values later. See here (emphasis mine):

    Non-whitespace character, except format specifier (%): Any character that is not either a whitespace character (blank, newline or tab) or part of a format specifier (which begin with a % character) causes the function to read the next character from the stream, compare it to this non-whitespace character and if it matches, it is discarded and the function continues with the next character of format. If the character does not match, the function fails, returning and leaving subsequent characters of the stream unread.

    You can ensure that it successfully read the values by checking the return value:

    On success, the function returns the number of items of the argument list successfully filled. This count can match the expected number of items or be less (even zero) due to a matching failure, a reading error, or the reach of the end-of-file.

    So in this case, your return value should be 2.

    If you want to print that text, you can use printf instead:

    printf("insert no in format x y");
    if (scanf("%f %f",&x,&y) != 2){
        printf("Error reading in the parameters!");
        return -1;
    };