[Solved] What is the difference between scanf (“%s”,a) scanf(“%[^\n]s”,a) and gets(a) for strings in C programming?


First of all, they all have undefined behavior for the same reason: They will read a number of characters you can’t know in advance, but through your pointer, you provide storage where to store this data, and this storage has some fixed size. Therefore, there are always inputs possible that will overflow your buffer. You should’nt ever use any of these lines in your code.

That said:

  • gets() reads a line of input and stores it to your buffer. It also reads the newline character, but this isn’t stored. This function is broken by design, as there is no way to use it safely. Don’t ever use it. It has been removed from the C standard in C11, so you could only use it with older standards anyways. The correct replacement is char a[100]; fgets(a, sizeof a, stdin);. This will store the newline character in the buffer, though.

  • scanf("%[^\n]s", ...) will also read a line of input. The [] conversion specifier takes a list of accepted or, with ^ in front, rejected characters. So with this syntax, it will accept any character except newline. Therefore, the newline character won’t be read this way. The s would be searched in the input literally, it’s not what you mean. s and [] are different conversion specifiers. To use this one correctly, you must use the field with like so: char a[100]; scanf("%99[^\n]", a);. Note that you have to specify one less than your buffer size because scanf() doesn’t count the '\0' character that’s appended as an end mark for the string.

  • scanf("%s", ...) reads a “word“, that is it stops at the first whitespace character. To use this correctly, as above, use something like char a[100]; scanf("%99s", a);.

3

solved What is the difference between scanf (“%s”,a) scanf(“%[^\n]s”,a) and gets(a) for strings in C programming?