cstringscanfformat-specifiersformat-conversion

Why my conversion specifiers doesn't work properly in C


I'am quite new in C and dealing with text formatting that is a bit challenging for me. I try to enter initials J. S. (whitespace between characters) and name John Smith and my initials array stores the value J. S.John Smith that is not what should be.

Can somebody explane me why it is happening.

Here is my code snippet ( just example )

#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>

struct Person
{
    char initials[5];
    char name[35];
};

int main(void)
{
    struct Person person;
    printf("Please enter symbols: ");
    scanf("%6[^\n]%*c", person.initials);
    printf("%s\n", person.initials);
    printf("Please enter your name: ");
    scanf("%35[^\n]%*c", person.name);
    printf("%s\n", person.name);
    printf("%s\n", person.initials);
}

Output :

Please enter symbols: J. S.
J. S.
Please enter your name: John Smith
John Smith
J. S.John Smith

Will be very thankful for help.


Solution

  • Your initials array isn't large enough to store what you're entering.

    The string "J. S." consists of 5 characters plus a terminating null byte for a total of 6 bytes. initials is only 5 bytes wide so you overrun the buffer.

    Also, the sizes you're using for the scanf formats is not correct. They should be one less than the size of the array to account for the terminating null byte when a string is read.

    Change initials to be large enough to hold the desired string:

    char initials[6];
    

    And change the formats to correctly state the largest string they can hold.

    scanf("%5[^\n]%*c", person.initials);
    scanf("%34[^\n]%*c", person.name);