Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting a #defined constant number to a string

I have a constant defined:

#define MAX_STR_LEN 100

I am trying to do this:

scanf("%" MAX_STR_LEN "s", p_buf);

But of course that doesn't work.

What preprocessor trick can be use to convert the MAX_STR_LEN numerica into a string so I can use it in the above scanf call ? Basically:

scanf("%" XYZ(MAX_STR_LEN) "s", p_buf);

What should XYZ() be ?

Note: I can of course do "%100s" directly, but that defeats the purpose. I can also do #define MAX_STR_LEN_STR "100", but I am hoping for a more elegant solution.

like image 887
Sid Datta Avatar asked Sep 29 '12 00:09

Sid Datta


People also ask

How do you convert to int in Python?

To convert, or cast, a string to an integer in Python, you use the int() built-in function. The function takes in as a parameter the initial string you want to convert, and returns the integer equivalent of the value you passed. The general syntax looks something like this: int("str") .

What is the best free PDF converter?

#1: PDFelement - Best PDF Converter Software PDFelement is the best free PDF converter for Windows 10, 8, 7, and Mac. can meet all your PDF needs. You can convert PDF to or from almost any popular file format, including Word, Excel, PowerPoint, images, text, HTML, and more.


1 Answers

Use the # preprocessing operator. This operator only works during macro expansion, so you'll need some macros to help. Further, due to peculiarities inherent in the macro replacement algorithm, you need a layer of indirection. The result looks like this:

#define STRINGIZE_(x) #x
#define STRINGIZE(x) STRINGIZE_(x)

scanf("%" STRINGIZE(MAX_STR_LEN) "s", p_buf);
like image 125
James McNellis Avatar answered Sep 20 '22 14:09

James McNellis