How can I print a quotation mark in C?

2019-01-07 17:01发布

问题:

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?

回答1:

Try this:

#include <stdio.h>

int main()
{
  printf("Printing quotation mark \" ");
}


回答2:

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.



回答3:

You have to escape the quotationmark:

printf("\"");


回答4:

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", '"', '"');


回答5:

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


回答6:

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.



回答7:

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.



回答8:

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

Output: "



回答9:

you should use escape character like this:

printf("\"");


标签: c printf