Montag, 18. November 2013

Multi line strings in C

I'm still trying to find some time to finish my second article about the Putty sources (first one is here).

In the meantime I want to share a helpful little trick on how to handle multi line strings in C with you. See this example:
//multi line strings and multi line printf examples
#include <stdio.h>

int main( void ) {

    // multi line string definition
    char* string1 = "i am "
                    "a multiline string "
                    "which the compiler assembles "
                    "to one sting. No need for "
                    "concatination.";

    printf( "An ordinary string on one line: %s\n", string1 );


    // multi line string inside printf
    char* string2 = "a string";

    printf( "Multiline string works also "
            "inside a printf command. "
            "This is helpful if the string part of "
            "the command is too long to fit your maximum "
            "collumn size. Of course you can use format "
            "specifier like %s.\n", string2 );
}
The output is:
An ordinary string on one line: i am a multiline string which the compiler assembles to one sting. No need for concatination.
Multiline string works also inside a printf command. This is helpful if the string part of the command is too long to fit your maximum collumn size. Of course you can use format specifier like a string.
The examples are (hopefully) self-explainatory. The first one simply defines a multi line string which will be printed on one line. The second example demonstrates that the printf family of commands also understands the multi line syntax. Neat, innit?

Keine Kommentare:

Kommentar veröffentlichen