Is there any way to format %s in scanf using not a nubmer but a variable/constant?

Viewed 67

I mean we have MAX_LENGTH value, so I want to cap the string formatting length using it but not a number like 12.

#include <stdio.h>
#define MAX_LENGTH 12

int main(void) {

    char first_name[MAX_LENGTH + 1], last_name[MAX_LENGTH + 1];

    printf("Пожалуйста, введите ваше имя:  ");
    scanf("%12s", first_name);
    
    char ch;                                      // Clearing the buffer to fix a bug when the input
    while((ch = getchar()) != '\n' && ch != EOF); // string lenght is greater than MAX_LENGTH.

    printf("Пожалуйста, введите фамилию:   ");    // So, I made it 12 just to show that in case of string length > 12
    scanf("%12s", last_name);                     // the program doesn't crash but just cuts the string.

    printf("Ваши данные: %s %s\n", last_name, first_name);

    return 0;
}

I'd wanted to do something like

printf("%.*s", MAX_LENGTH, string); 

but with the scanf function. Just to not be fixing it every time I change MAX_LENGTH.

1 Answers

You can use any string as a format of the scanf. It can be also a variable.

#include <stdio.h>

int main(void)
{
    char format[16];
    char string[16];
    size_t maxLength;

    if(scanf("%zu", &maxLength) != 1) { /* handle error */}

    sprintf(format, "%%%zus", maxLength);
    if(scanf(format, string) != 1) { /* handle error */}

    printf("`%s`\n", string);
}

Result:

`12345`
Related