Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

CPP how to escape a quotation mark

I'm in the process of making code from 1991 work on Ubuntu 19.

I've got this file I need to run through CPP where I am forced to use the -traditional option.

#define ITEM_WEAPON 5
#define ITEM_FIREWEAPON 6
Trade types = "+ITEM_WEAPON+ITEM_FIREWEAPON+"

I want the line to become

Trade types = "+5+6+"

This worked just fine in 1991-1997 ;-) It seems cpp for obvious reasons no longer parse between quotation marks.

I've tried to escape the quotes using the backslash character e.g.

Trade types = \""+ITEM_WEAPON+ITEM_FIREWEAPON+\""

But still haven't found a good solution.

For clarity this is not a C program, instead we simply used cpp to expand various macros into a structured text file which was later run through a parser.

The closest I have come (with -traditional flag) to something that almost works is this:

#define WI 1
#define WJ 2

#define T(a,b) Trade types = "+a+b+"
T(1,2)
T(WI,WJ)

Which outputs:

Trade types = "+1+2+"
Trade types = "+WI+WJ+"

So the pre-processor does substitute the arguments between the quotes but does not expand the parametized macro.

like image 955
Michael Seifert Avatar asked Feb 02 '26 02:02

Michael Seifert


2 Answers

#include <iostream>
#include <string>

#define ITEM_WEAPON 5
#define ITEM_FIREWEAPON 6

#define STRINGIFY_HELPER(x) #x
#define STRINGIFY(x) STRINGIFY_HELPER(x)


int main()
{
    std::string types = "+" STRINGIFY(ITEM_WEAPON) "+" STRINGIFY(ITEM_FIREWEAPON) "+";
    std::cout << types << '\n';
    return 0;
}

https://wandbox.org/permlink/R5sLKvGhcnL9Jgyj

like image 166
Marek R Avatar answered Feb 05 '26 08:02

Marek R


With more macros you can do that:

#define ITEM_WEAPON 5
#define ITEM_FIREWEAPON 6

#define MAKESTRING2(s) #s
#define MAKESTRING(s) MAKESTRING2(s)

Trade types = "+" MAKESTRING(ITEM_WEAPON) "+" MAKESTRING(ITEM_FIREWEAPON) "+";

But I also would try avoiding macros:

#define ITEM_WEAPON 5
#define ITEM_FIREWEAPON 6

const std::string types = "+" + std::to_string(ITEM_WEAPON) +  "+" + std::to_string(ITEM_FIREWEAPON) + "+";

Or even better:

constexpr int ITEM_WEAPON = 5;
constexpr int ITEM_FIREWEAPON = 6;

const std::string types = "+" + std::to_string(ITEM_WEAPON) +  "+" + std::to_string(ITEM_FIREWEAPON) + "+";
like image 32
Gerhard Stein Avatar answered Feb 05 '26 10:02

Gerhard Stein



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!