Use Of (space) To Take Input Of String

- 1 answer

I am using a Windows 10 machine and codeblocks as IDE. In a code, I saw using whitespace character (space) for taking input of a string like

scanf(" %[^\n]", s);

what is the reason behind it?


int main()
    int t, i, j, temp, len;
    char s[1002];

    scanf("%d", &t);

        scanf(" %[^\n]", s);
        len = strlen(s);
        for(i = 0, j = (len-1); i < (len/2); i++, j--){
            temp = s[i];
            s[i] = s[j];
            s[j] = temp;

        printf("%s\n", s);

    return 0;

In this program, the programmer just tried to replace the components of the string



The space in the beginning of " %[^\n]" matches any number of white space characters ' ', '\t', '\n', etc. in the input, and skips them

Note that for scanf specifically, most format specifiers skip white space by design, so do not need the leading space, but three don't:

`%n`   — count of characters processed
`%[…]` — scan set
`%c`   — read char.

The second part of your expression, is a scan set, and is relevant to this discussion in that as written can invoke undefined behavior if input to the scanf() call is too long.
%[^\n] matches all characters except the newline (\n), so stores it along with the terminating \0 into s. If input happens to be longer than s (in this case > 1001) there will be no room for the terminating '\0', thus resulting in a char array without a null termination. This by itself is not undefined behavior, but calling len = strlen(s); on the next line will be.

So, given the maximum input length char s[1002]; can hold is 1001 (leaving room for '\0') then, a safer expression would be:

scanf(" %1001[^\n]", s);

which limits input length to the value following %, thus leaving room for placement of null terminator.