2012-08-02 62 views
18

在接受采访时有人问我如何在C中打印引号?

打印使用printf()功能

我不知所措一个引号。即使在他们的办公室里有一台电脑,他们告诉我试试看。我想是这样的:

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

但我怀疑它不会编译。当编译器得到第一个"它认为它是字符串的结尾,而不是。那么我怎么能做到这一点?

+12

还记得那本书开头的转义字符的短节吗? – chris 2012-08-02 06:41:37

+0

可能重复的[如何在C中显式地打印特殊字符?](http://stackoverflow.com/questions/29477345/how-to-print-special-characters-explicitly-in-c) – 2016-09-01 04:26:39

回答

22

试试这个:

#include <stdio.h> 

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

你必须逃离quotationmark:

printf("\""); 
4

你必须使用逃逸字符。这是鸡与鸡蛋问题的解决方案:如果我需要它来编写一个“,如果我需要它来终止字符串文字?那么,C创建者决定使用改变下一个字符的处理的特殊字符:

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

您也可以使用 '\' 像 “\ n”, “\ t”, “\ A” 输入特殊符号,输入 '\' 本身: “\\” 等

7

除了转义字符,您也可以使用格式%c,并使用字符文字的引号。

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

它的非常好的方式打印字符常量。 – Angus 2012-08-02 07:15:39

16

没有反斜线,特殊字符具有自然特殊的含义。用反斜杠打印出来。

\ - 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 

printf(" \" "); 

将打印您的报价声明。 您也可以在前面打印(斜杠)这些特殊字符\ a,\ b,\ f,\ n,\ r,\ t和 \ v。

+0

'\%'是错误的 - 它将被视为与'%'相同。 '\''是不需要的 - 你可以在双引号内加一个引号。 – ugoren 2012-08-02 08:43:18

+1

好的catch.But你不能在双引号内打印%。但是,您可以使用%%打印百分比符号。像printf(“%%”); – Angus 2012-08-02 09:01:47

+1

如果它不在格式字符串中,你也可以自由使用'“%”(例如'printf(“用%s打印一个int \ n”,“%d”)') – ugoren 2012-08-02 09:06:32

1

这其中也适用:

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

但是,如果你计划在采访中使用它,请确保您能解释一下它的作用。

编辑:继埃里克Postpischil的评论,下面是不依赖于ASCII版本:

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

输出是不是很好,它仍然不是100%便携式(会打破一些假设的编码方案),但它应该在EBCDIC上工作。

+0

这是错误的。首先执行内部printf,然后执行外部printf。通常使用嵌套的printf来查找控制台中打印的字符总数。 – Angus 2012-08-02 09:36:08

+1

这没有错,只是有点扭曲,而且效果很好。尝试一下。正如你所说,内部printf首先被执行,外部 - 它有什么问题? – ugoren 2012-08-02 10:27:46

+0

它将打印从内部printf输出的数字的ascii值(打印的字符数)。 – Angus 2012-08-02 10:39:57

7

在C编程语言中,\被用来打印一些在C中有特殊含义的特殊字符。这些特殊字符如下所列

\\ - Backslash 
\' - Single Quotation Mark 
\" - Double Quatation Mark 
\n - New line 
\r - Carriage Return 
\t - Horizontal Tab 
\b - Backspace 
\f - Formfeed 
\a - Bell(beep) sound 
0
#include<stdio.h> 
int main(){ 
char ch='"'; 
printf("%c",ch); 
return 0; 
} 

输出: “

-1

你应该使用: 的printf(” \ “”);