2013-06-05 31 views
2

我寫了這個程序,試圖理解C稍微好一點。它可以工作,但由於某種原因,在正確輸出之前打印(null)。我的代碼:爲什麼我的C程序在執行字符轉換時打印「(null)」?

/* This program will take a string input input from the keyboard, convert the 
string into all lowercase characters, then print the result.*/ 

#include <stdio.h> 
#include <string.h> 
#include <ctype.h> 

int main() 
{ 
    int i = 0; 
    /* A nice long string */ 
    char str[1024];        
    char c; 
    printf("Please enter a string you wish to convert to all lowercase: "); 

    /* notice stdin being passed in for keyboard input*/ 
    fgets(str, 1024, stdin); //beware: fgets will add a '\n' character if there is room  

    printf("\nYour entered string: \n\n%s\n", str); 
    printf("\nString converted to lowercase: \n\n%s\n"); 
    while(str[i]) { //iterate str and print converted char to screen 
     c = str[i]; 
     putchar(tolower(c)); 
     i++; 
    } 
    putchar('\n'); //empty line to look clean 
    return 0; 
} 

順便說一句,我注意到,當如果我的字符串變量添加到最後一個printf函數,問題消失。

替換:

printf("\nString converted to lowercase: \n\n%s\n"); 

printf("\nString converted to lowercase: \n\n%s\n, str"); 

下面是該問題的樣本輸出:

Please enter a string you wish to convert to all lowercase: THE QUICK BROWN FOX 
JUMPED OVER THE LAZY DOG. 

Your entered string: 

THE QUICK BROWN FOX JUMPED OVER THE LAZY DOG. 


String converted to lowercase: 

(null) 
the quick brown fox jumped over the lazy dog. 

Press any key to continue . . . 
+0

我剛纔試了一下你PROG沒有看到任何(空) – Satya

+0

@Satya,這個程序會導致未定義的行爲,所以如果你嘗試它,你可能會(可能?)看到不同的行爲。 –

+0

非常感謝@CarlNorum對這樣美麗的解釋 – Satya

回答

6

這print語句:

printf("\nString converted to lowercase: \n\n%s\n"); 

在格式字符串中有一個%s,但是您沒有傳遞參數以匹配它。

幸運的是,0恰好會通過,並且您的printf實施通過打印(null)正常處理。您處於未定義的行爲區域。

如果你打開更多的警告標誌,你的編譯器可能會警告你這類問題。在一個快速測試在這裏,鏘甚至不需要任何標誌:

$ clang example.c -o example 
example.c:20:51: warning: more '%' conversions than data arguments [-Wformat] 
    printf("\nString converted to lowercase: \n\n%s\n"); 
               ~^ 
1 warning generated. 

我也沒有GCC:

$ gcc example.c -o example 
example.c: In function ‘main’: 
example.c:20: warning: too few arguments for format 
example.c:20: warning: too few arguments for format 
+0

啊,重複使用打印語句的危險。我不敢相信我盯着那條線,沒有明白。謝謝! – Johnny

+0

我正在使用Visual Studio 2012.不知道如何讓它爲此發出警告。 – Johnny

相關問題