0

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...

0

3 Answers 3

1

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

Sign up to request clarification or add additional context in comments.

Comments

0

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.

Comments

0

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.