C string new line
A classic!
In C, a newline character is represented by the character \n
. This is a special character that tells the terminal or console to move to the next line.
Here are a few ways to include a newline character in a C string:
-
Using the
\n
escape sequence:char str[] = "Hello\nWorld!";
This will create a string with the text "Hello" followed by a newline character, and then the text "World!".
-
Using the
printf
function:printf("Hello\nWorld!\n");
This will print the string "Hello", followed by a newline character, followed by the string "World!", and finally another newline character.
-
Using the
puts
function:puts("Hello\nWorld!");
This will print the string "Hello\nWorld!" followed by a newline character.
-
Using the
sprintf
function:char str[20]; sprintf(str, "Hello\nWorld!");
This will create a string buffer
str
and fill it with the text "Hello\nWorld!".
Note that in all cases, the \n
character is a single character, not a string. It's a special character that tells the terminal or console to move to the next line.