Home > OS >  Using scanf %c fills string with garbage characters
Using scanf %c fills string with garbage characters

Time:12-28

I will give a input and the output will be the as same as input. But the output is not showing properly. I have given the code here and also an input and output for example.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main()
{
    char s[40];
    scanf("%c", &s);
    printf(s);

    return 0;
}

Input: love
Output: l   Φ■`

Why this is happening?

CodePudding user response:

Since you are getting a string as input, use %s formatter instead of %c. %c can only get a single character from the stdin and is not null terminated. So scanf only fills the first value of the string, that is s[0] in this case. Since the string is not closed by a null terminator (\0), the printf continues to print whole array including the garbage values already present in the memory.

Optionally you can use %s formatter in printf to ensure that the output is formatted as a string.

#include <stdio.h>
#include <string.h>
#include <math.h>
#include <stdlib.h>

int main()
{
    char s[40];
    scanf("%s", &s);
    printf("%s", s);

    return 0;
}

CodePudding user response:

%c reads a single character. The "garbage" characters you are seeing is an expression of undefined behavior; it is pointless to speculate about UB, but what you are seeing is the (uninitialized) data that happened to be in the 2nd and remaining characters of the buffer. You could avoid the "garbage" by initialing s with char s[40] = "", but probably you want to use %s. Since the array into which you are reading data is of size 40, you can only read up to 39 characters. You must check the value returned by scanf. If scanf does not read any data, the s remains uninitialized and attempting to read it is undefined behavior. You ought not call printf(s), since s is unknown data and may contain formatting. It would probably be wiser to use fputs or puts. For example:

int main(void)
{
    char s[40];
    if( scanf("9s", &s) == 1 ){
        printf("%s\n", s);
    }

    return 0;
}
  • Related