alessandro_pier
alessandro_pier

Reputation: 13

Usage of scanf for strings in C

Hello everyone I've a problem with this code:

#define MAX_LIMIT 5
#include <stdio.h>
#include <stdlib.h>
int main()
{
    char S[MAX_LIMIT];
    scanf("%s", S);
    printf("%s\n", S);
}

As you can see the "MAX_LIMIT" value is 5 so I don't want the sting "S" to have more than 5 chars... The problem occurs when I give in input words which exceed this limit.

For example, if I wrote "1234567890" I expect the printf to print "1234" but it prints "1234567890" and I don't know why... I've also tried to add fflush(stdin); or getchar(); after the input but it doesn't work

I've tried with fgets(S, MAX_LIMIT, stdin); and it works but I still don't understand why if I use scanf it doesn't...

Upvotes: 0

Views: 157

Answers (3)

Chris Dodd
Chris Dodd

Reputation: 126536

You need to put the limit in the scanf format string:

scanf("%4s", S);

Note that the limit is one less than the size of the array (as space is needed for the terminating NUL which is not counted as one of the input characters), and it needs to be directly in the string as an integer (making it hard to use a symbolic or variable length). Also, if the input has more than 4 (non-whitespace) characters, only the first 4 will be read and the rest will be left in the input buffer to be read later.

Upvotes: 0

LSerni
LSerni

Reputation: 57453

The first problem is that scanf is not limited - it has no way of knowing the actual size of the input buffer (how could it? the variable S doesn't bring along its size). You can force scanf to read no more than a given number of characters with an appropriate format, but then the format has to be hard-coded (you can modify it at runtime, but the code grows clunkier).

Then, char S[MAX_LIMIT] will allocate at least MAX_LIMIT characters, but this number might be both rounded upwards for optimization purposes by the compiler (giving you an untrustworthy, platform-dependent "buffer"), and allocated in a writeable area, so that you are overwriting information with the extra input. Until the extra information is needed or reinitialized, you might notice nothing amiss.

To avoid these problems, you might for example use fgets, and then run sscanf on the resulting buffer.

Upvotes: 0

Albus_Dalbador
Albus_Dalbador

Reputation: 61

try to use fgets function instead of scanf https://www.tutorialspoint.com/c_standard_library/c_function_fgets.htm

Upvotes: 1

Related Questions