2

I want to limit the number of chars scanf command will get using a define value. The following code worked well

scanf("%20s",&stud->student_name);

but then i have tried that one (MAXNAMELEN is defiend as 20)

scanf("%MAXNAMELENs",&stud->student_name);

and it didn't work. how can I do that using scanf only ?

saar13531
  • 105
  • 2
  • 8

1 Answers1

1

A pair of defines allow for stringifying another define

#define MAXNAMELEN 20
#define LENSTR_(x) #x
#define LENSTR(x) LENSTR_(x)

use as

char str[MAXNAMELEN + 1] = "";
result = scanf ( "%"LENSTR(MAXNAMELEN)"s", str);
user3121023
  • 8,181
  • 5
  • 18
  • 16