Skip to main content
gamedev.net
🔒 Locked

[C++ macro] String operation

Started by Klarre Apr 11, 2007 at 7:25 AM 3 replies 1.1k views
Original Post
Klarre
Klarre
How should I write the ADD_WITH_SPACE macro to get the output "foo bar"? Thanks for your help!
#include <iostream>
#include <string>

// HOW SHOULD THIS MACRO BE WRITTEN TO GIVE THE OUTPUT "foo bar"???
#define ADD_WITH_SPACE(a, b) #a## #b

int main()
{
	std::cout << ADD_WITH_SPACE(foo, bar) << std::endl;

	std::cin.get();

	return 0;
}


http://www.klarre.se
Klarre
Klarre
I solved it...

#define ADD_WITH_SPACE(a, b) #a##" "#b


...but, now. How do I make it print "foo bar" including the " signs? Is that possible in some way?
http://www.klarre.se
Bregma
Bregma
Quote:
Original post by Klarre...but, now. How do I make it print "foo bar" including the " signs? Is that possible in some way?

I'm really not sure what you're trying to do, but this C preprocessor macro
#define ADD_WITH_SPACE(a, b) "\""#a" "#b"\""

gives this output:
"foo bar"

quotes and all.

--smw
Stephen M. Webb
Professional Free Software Developer
Klarre
Klarre
Thanks! That was what I wanted!
http://www.klarre.se
Zahlman
Zahlman
This works by relying on the preprocessor's behaviour of automatically concatenating adjacent string literals in the source code. The macro expands, after the stringizing is done, and putting spaces between each literal for clarity, as "\"" "foo" " " "bar" "\"". The preprocessor joins up all the adjacent string literals to get "\"foo bar\"", where of course the \"s are escape sequences representing actual double-quote characters within the literal.

Topic Locked

This topic has been locked by a moderator. New replies are not allowed.

Sign in to reply to this topic.