簡體   English   中英

了解我的邏輯,如果我用c語言編寫代碼呢? 37行/代碼空間

[英]understand my logic of my while do if code in c ? 37 lines/spaces of code

我編寫的代碼基本上是一個有關要求用戶在其中輸入名字的問題。 如果名稱為空,即用戶忘記輸入那里的名字,則該代碼將提及用戶忘記輸入那里的名字,然后再次詢問。 它應該繼續詢問直到滿足條件。

// 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!任何人都可以舉一個不同的示例,它確實起作用,我可以更好地理解它嗎?

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

並不是您遇到的問題,而是您很快就會遇到的一個問題:

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

如果字符串相等,則strcmp返回0;如果字符串不同,則返回正或負值。

這意味着,如果你嘗試解釋結果作為布爾, strcmp返回true當字符串是不同的 ,而false時,他們是相同的

您現在可以在引號上看到問題了嗎?

正如Blagovest Buyukliev所提到的,您需要將fget放入循環中。 而且,fgets將在字符串中包含返回字符(請參閱此處 ),因此將其與“”進行比較的調用將無法按您期望的那樣工作。

您可以將其與“ \\ n”進行比較。 或使用gets ,其中不包括換行符。

另外,確實沒有理由針對NULL檢查名字,它是一個堆棧變量,並且永遠不會為NULL。 並且,最后,只有當某人的名字實際上是“ firstname”時,您的printf才會執行,因為這就是您要比較的東西。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM