Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

scanf / field lengths : using a variable / macro, C/C++

Tags:

c++

c

field

scanf

How can I use a variable to specify the field length when using scanf. For example:

char word[20+1];
scanf(file, "%20s", word);

Also, is it correct to use 20+1 (since it needs to add a \0 at the end?). Instead, I'd like to have something like:

#define MAX_STRING_LENGTH 20

and then

char word[MAX_STRING_LENGTH+1];
scanf(file, "%"MAX_STRING_LENGTH"s", word); // what's the correct syntax here..?

Is this possible? How about if it's a variable like:

int length = 20;
char word[length+1];
scanf(file, "%" length "%s", word); // what's the correct syntax here..?

Thanks.

like image 522
user51231 Avatar asked Jul 21 '10 16:07

user51231


1 Answers

The following should do what you need for the first case.

#define MAX_STRING_LENGTH 20
#define STRINGIFY(x) STRINGIFY2(x)
#define STRINGIFY2(x) #x

{
  ...
  char word[MAX_STRING_LENGTH+1];     
  scanf(file, "%" STRINGIFY(MAX_STRING_LENGTH) "s", word);
  ...
}

NOTE: Two macros are required because if you tried to use something like STRINGIFY2 directly you would just get the string "MAX_STRING_LENGTH" instead of its value.

For the second case you could use something like snprintf, and at least some versions of C will only let you allocate dynamically sized arrays in the heap with malloc() or some such.

like image 115
torak Avatar answered Nov 03 '22 11:11

torak