Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Defining a string over multiple lines

Tags:

c

syntax

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?

like image 340
Nanomurf Avatar asked Oct 02 '12 17:10

Nanomurf


People also ask

How do you define multiline strings?

Use triple quotes to create a multiline string It is the simplest method to let a long string split into different lines. You will need to enclose it with a pair of Triple quotes, one at the start and second in the end. Anything inside the enclosing Triple quotes will become part of one multiline string.

How do I write a string to multiple lines in Java?

If you want your string to span multiple lines, you have to concatenate multiple strings: String myString = "This is my string" + " which I want to be " + "on multiple lines."; It gets worse though. If you want your string to actually contain new lines, you need to insert \n after each line.

How do you define a long string?

Long strings can be written in multiple lines by using two double quotes ( “ “ ) to break the string at any point in the middle.


1 Answers

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..");
like image 114
pb2q Avatar answered Oct 06 '22 08:10

pb2q