bitm0de
Active Member
- Joined
- May 24, 2015
- Messages
- 13
- Reaction score
- 0
If you are choosing to parse strings with scanf(), maybe because you don't want to deal with the issues of '\n' with fgets() (even though there are still issues with scanf() aside from it being a more expensive function to call for grabbing a string without any special format because the format string needs to be read by the function to determine what data goes into each following variable argument), then you should be using a length modifier. The issue here is that you aren't able to use a wildcard, and you can't just concatenate some numeric value or variable directly into the string like in other languages... You would have to programmatically parse it into the format string passed to the function which is a bit of work, or just hardcode it into the string literal, which may not always be the best case scenario if you want something to be a bit easier to manage should you ever have to change the size of the buffer, because then you have to go in and manually change the value within the string too. An alternative to make this easier is to use macros.
What happens here is we've defined a MAX_LENGTH constant to be the max length of the input (without the null terminator). So we allocate a buffer with MAX_LENGTH + 1 to allocate enough space for the terminator, and tokenize this value into a string using the preprocessor so that it can be part of the format string before the code is compiled.
In this case, our buffer allows for 101 elements, where index [100] is reserved for the null terminator, and our scanf() call with the preprocessed format string would then look like:
Perfect! Now we can modify the size of our allocated buffer and the format string easily all by just changing one constant value here:
Code:
#include <stdio.h>
#define STRTOKEN(x) #x
#define STR(x) STRTOKEN(x)
#define MAX_LENGTH 100
int main(void)
{
char buf[MAX_LENGTH + 1];
scanf(" %" STR(MAX_LENGTH) "s", buf);
return 0;
}
What happens here is we've defined a MAX_LENGTH constant to be the max length of the input (without the null terminator). So we allocate a buffer with MAX_LENGTH + 1 to allocate enough space for the terminator, and tokenize this value into a string using the preprocessor so that it can be part of the format string before the code is compiled.
In this case, our buffer allows for 101 elements, where index [100] is reserved for the null terminator, and our scanf() call with the preprocessed format string would then look like:
Code:
scanf(" %100s", buf);
Perfect! Now we can modify the size of our allocated buffer and the format string easily all by just changing one constant value here:
Code:
#define MAX_LENGTH 100