Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

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

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.

over 4 years ago · Santiago Trujillo
1 Respuestas
Responde la pregunta

0

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`
over 4 years ago · Santiago Trujillo Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda