Nanomurf
Nanomurf

Reputation: 759

Defining a string over multiple lines

Please take the following:

char buffer[512];

memset(buffer, 0, sizeof(buffer));
sprintf(&buffer[0],"This Is The Longest String In the World that in text goes on and..");

printf("Buffer:%s\r\n",buffer);

I would like to be able to create this string over multiple lines, for ease of troubleshooting and editing. However, when I use the \ command my output is separated by what appear to be tabs?

Example:

sprintf(&buffer[0],"This Is The\
    Longest String In the World\
    that in text goes on and..");

yields an output of:

Buffer:This Is The        Longest String In the World       that in text goes on and..

Any ideas? Is this just an incorrect approach to try to break up a string across multiple lines of code?

Upvotes: 17

Views: 26183

Answers (3)

pb2q
pb2q

Reputation: 59637

The newline continuation takes into account any whitespace within the code.

You can take advantage of string literal concatenation for better readability:

sprintf(buffer, "This Is The "
                "Longest String In the World "
                "that in text goes on and..");

Using \ you'll need to begin the continuation of your string at column 0:

sprintf(buffer, "This Is The \
Longest String In the World \
that in text goes on and..");

Upvotes: 26

Joseph Quinsey
Joseph Quinsey

Reputation: 9972

Although this may seem pedantic, I've been bitten enough times in the real world to have the following issues with the other two posted answers.

  • The two posted answers neglect to give spaces between words joining the separate string literals (obvious, after the first test).

  • If your string is really long, use snprintf() instead--it is slightly clumsier, but it tells anyone reviewing your code that you are aware of common dangers in code maintenance.

  • If your string happens to contain %, you'll get a compiler warning (good) or random segmentation faults (bad). So use "%s" or, perhaps in this case, just strcpy(). (In two months' time, a co-worker could easily add 99.9% to the message.)

  • The use of memset(), which I see often, is just cargo-cult programming. Yes, in special cases one needs it, but using it all the time sends the wrong message.

  • And finally, why would anyone use &buffer[0] when just buffer would do?

So to summarize, your code should perhaps read:

char buffer[512];
snprintf(buffer, sizeof buffer, "%s", 
   "This is The Longest String "
   "In the World that in text "
   "goes on and on and on and on ....");
printf("Buffer:%s\r\n", buffer);

Upvotes: 9

Vikdor
Vikdor

Reputation: 24134

This too would just work as well:

char buffer[512];
sprintf(&buffer[0], "This is the longest string"
        "in the world that in text"
        "goes on and on and on and on ....");
printf("%s\n", buffer);

Upvotes: 4

Related Questions