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

273
Views
¿Hay alguna forma de formatear %s en scanf usando no un número sino una variable/constante?

Quiero decir que tenemos el valor MAX_LENGTH, por lo que quiero limitar la longitud del formato de la cadena usándolo, pero no un número como 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; }

Quería hacer algo como

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

pero con la función scanf. Solo para no arreglarlo cada vez que cambio MAX_LENGTH.

over 4 years ago · Santiago Trujillo
1 answers
Answer question

0

Puede usar cualquier cadena como formato del scanf . También puede ser una 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); }

Resultado:

 `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!