[c] How can I print a quotation mark in C?

In an interview I was asked

Print a quotation mark using the printf() function

I was overwhelmed. Even in their office there was a computer and they told me to try it. I tried like this:

void main()
{
    printf("Printing quotation mark " ");
}

but as I suspected it doesn't compile. When the compiler gets the first " it thinks it is the end of string, which is not. So how can I achieve this?

This question is related to c printf

The answer is


you should use escape character like this:

printf("\"");

This one also works:

printf("%c\n", printf("Here, I print some double quotes: "));

But if you plan to use it in an interview, make sure you can explain what it does.

EDIT: Following Eric Postpischil's comment, here's a version that doesn't rely on ASCII:

printf("%c\n", printf("%*s", '"', "Printing quotes: "));

The output isn't as nice, and it still isn't 100% portable (will break on some hypothetical encoding schemes), but it should work on EBCDIC.


Besides escaping the character, you can also use the format %c, and use the character literal for a quotation mark.

printf("And I quote, %cThis is a quote.%c\n", '"', '"');

In C programming language, \ is used to print some of the special characters which has sepcial meaning in C. Those special characters are listed below

\\ - Backslash
\' - Single Quotation Mark
\" - Double Quatation Mark
\n - New line
\r - Carriage Return
\t - Horizontal Tab
\b - Backspace
\f - Formfeed
\a - Bell(beep) sound

You have to use escaping of characters. It's a solution of this chicken-and-egg problem: how do I write a ", if I need it to terminate a string literal? So, the C creators decided to use a special character that changes treatment of the next char:

printf("this is a \"quoted string\"");

Also you can use '\' to input special symbols like "\n", "\t", "\a", to input '\' itself: "\\" and so on.


You have to escape the quotationmark:

printf("\"");

#include<stdio.h>
int main(){
char ch='"';
printf("%c",ch);
return 0;
}

Output: "


Without a backslash, special characters have a natural special meaning. With a backslash they print as they appear.

\   -   escape the next character
"   -   start or end of string
’   -   start or end a character constant
%   -   start a format specification
\\  -   print a backslash
\"  -   print a double quote
\’  -   print a single quote
%%  -   print a percent sign

The statement

printf("  \"  "); 

will print you the quotes. You can also print these special characters \a, \b, \f, \n, \r, \t and \v with a (slash) preceeding it.