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