Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

279
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!