Page 1 of 1

Hilarious printf solution

Posted: Wed Apr 06, 2016 12:40 pm
by Baker
I hate this ...

printf ("name is \"%s\"", name)

I hate writing it. I hate reading it. Messing up the escapes seems to happen some of the time.

My solution:

printf ("name is" _QUOTED, name); // _ means leading space

Code: Select all

#define _QUOTED_ " \"%s\" " // leading and trailing space form
#define _QUOTED " \"%s\""   // leading space form
#define QUOTED_ "\"%s\" " // trailing space form 


Or leading and trailing ...

printf ("I think his name was" _QUOTED_ "bob", name);

Or just trailing ...

printf ( QUOTED_ "is his name", name);

Re: Hilarious printf solution

Posted: Wed Apr 06, 2016 1:01 pm
by frag.machine
I used to suffer a lot with missing quotes in my beginning in C but nowadays muscle memory (most of time) protects me from silly mistakes.
But TBH when you work with languages that support string builders you realize how ugly printf is:

Code: Select all

  StringBuilder sb= new StringBuilder();
  sb
    .append(player.netname)
    .append(" left the game with ")
    .append(player.frags)
    .append(" frags.\n");

System.out.println (sb.toString());

Re: Hilarious printf solution

Posted: Wed Apr 06, 2016 1:32 pm
by Baker
No argument here. printf in C is not nice at all.

Re: Hilarious printf solution

Posted: Wed Apr 06, 2016 10:49 pm
by Spike
raw strings:
printf(R"(Hello "%s", your file is in "c:\program files\etc" or something. crap example)", name);
good for regex, but % still needs to be doubled up.

Re: Hilarious printf solution

Posted: Thu Apr 07, 2016 12:29 pm
by Baker
Looks like a gnu extension and a C++ thing so might actually work with most of the C compilers anyone actually uses including Microsoft's, despite not being part of the C language as far as I have been able to determine.