2011-01-10 73 views
0

我寫的代碼基本上是一個關於要求用戶輸入名字的問題。如果名字是空白的,即用戶忘記輸入名字,那麼代碼會提到用戶忘記輸入名字,然後再詢問。它應該繼續詢問,直到滿足條件。明白我的邏輯,而如果代碼在C? 37行/空格的代碼

// This sample compares user input to what is being typed. If the 
// input is void of any charicters before pressing enter, it will print a reply. 

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

int main() 
{ 
    char firstname[25]; 

    printf("Please enter your first name:"); 
    fgets(firstname,25,stdin); 

    // ask to enter in a name. If no name or text is present, 
    // will reply with no name entered 
    // and will loop untill a name is pressed and entered 

    do 
    { 
     printf("You pressed enter before entering your first name.\n Please enter first name");    
    } 
    while (firstname == NULL || strcmp(firstname,"")==0); 

    if(!strcmp(firstname, "firstname")) 
    { 
     printf("Thank you %s! for entering in your first name",firstname); 
    } 

    getchar(); 
} 

它只循環一次。所以,不知道爲什麼它不會繼續,並打破循環說"thank you %s! 任何人都可以給一個不同的例子,所以它的工作,我可以更好地理解它?

+0

它已經搞砸了! :)正確使用語法過濾器 – 2011-01-10 21:35:39

+1

保持縮進清晰!我已經寫了近10年的代碼,當你編寫這樣的代碼時,我有一段不可能讀的時間。如果一位經驗豐富的程序員閱讀這篇文章時遇到困難,那麼是什麼讓你覺得你會更容易? – riwalk 2011-01-10 21:37:33

回答

1

do...while循環中,只有一個printf語句不會更改循環的條件。考慮在循環內移動線fgets(firstname,25,stdin)

0

不太您遇到的問題,但它是一個你很快會遇到:

if(!strcmp(firstname, "firstname")) 

strcmp返回0,如果字符串相等的,如果它們是不同的返回正值或負值。

這意味着,如果你嘗試解釋結果作爲布爾值,strcmp回報true當琴絃不同false時候都相同

你現在可以在引用的行上看到問題嗎?

0

正如Blagovest Buyukliev所提到的,您需要將您的fgets移動到循環中。而且,fgets將在字符串中包含返回字符(請參閱here),因此將其與「」比較的調用不會像您期望的那樣工作。

您可以將它與「\ n」進行比較。或者使用gets,它不包含換行符。

另外,真的沒有理由檢查NULL的名字,它是一個堆棧變量,並且永遠不會爲NULL。而且,最後你的printf只會在別人的名字字面上是「firstname」時執行,因爲這就是你正在比較的。