2012-08-02 59 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(」 \ 「」);