[英]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
時,他們是相同的 。
您現在可以在引號上看到問題了嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.