Mohit M
Mohit M

Reputation: 29

Using \ as a literal exactly before \n in a string in printf

I'm stuck there because I can't use both at the same time: printf(" /\n");

You might get an idea what I'm trying to do :) Any help appreciated.

Upvotes: 1

Views: 856

Answers (2)

"I want to make a triangle by printing those aligned printf statements."

I think what you want is something like that:

printf("/\\\n");

Output:

/\

(Note: The empty line is intended)

Online example

Read from left to right, The first two \ (\\) denote the \ character. The third \ belongs to the newline character (\n).

Upvotes: 2

Abhishek Bhagate
Abhishek Bhagate

Reputation: 5766

You could print the single backslash before a newline in the following way -

printf("Hi\\\nHello");

Output :

Hi\
Hello

The first backslash will be ignored, the second one will be printed and then the newline character will be printed. \ is used for declaration of an escape sequence. You could also use backslash in a similar way if you want to print other characters like " using printf("\""); .


Using \ as a literal exactly before \n in a string in printf

printf("\\\n"); 

Output :

\

Hope this solves the issue !


Edit :

Here's your triangle :) -

printf("   /\\\n  /  \\\n /    \\\n/      \\\n--------");

Output :

   /\
  /  \
 /    \
/      \
--------

You could also do it using loops though, which would be much better than this.

Upvotes: 3

Related Questions