簡體   English   中英

為什么我的代碼在第一個 if 語句處中斷?

[英]Why does my code break at the first if statement?

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

int main (void)
{
    char *names;
    int capacity = 0;
    int size = 0;
    char name[100];

    printf ("Enter number 4 is you want to stop inputting names.\n");

    while (1)
    {
        printf ("Input:\n");
        fgets(name, sizeof(name),stdin);
        printf ("%s", name);

        if (strcmp(name, "end")!= 0)
        {
            printf ("hello");
        }

        if (strcmp (name, "end")== 0)
        {
            printf("bye ");
        }
    }
}

我試圖保持循環以獲取用戶輸入並在用戶輸入某個字符或單詞時跳出循環。 但是當我輸入“end”時,我希望輸出是“bye”,但輸出是“hello”。

問題很微妙。 閱讀fgets文檔 然后在調用fgets后查看調試器中name的值。

fgets在看到換行符時結束輸入,它在結果中包含換行符。 所以name以字符串"end\\n" 將其與"end"進行比較將失敗。

如果要使用fgets ,則必須允許使用該換行符,並與"end\\n"進行比較。

如果這是 C 代碼,請使用scanf 如果這是 C++ 代碼, std::cin與流提取器一起使用。

這是由您的輸入函數fgets引起的。 改用cin ,一旦輸入“ end ”,您將獲得預期的輸出“ bye ”。

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

  using namespace std; 

  int main (void) {

    char *names;
    int capacity = 0;
    int size = 0;
    char name[100];

    printf ("Enter number 4 is you want to stop inputting names.\n");

    while (1)
    {
        printf ("Input:\n");
        cin >> name;
        printf ("%s", name);

     if (strcmp(name, "end")!= 0)
     {
         printf ("hello");
     }

     else if (strcmp (name, "end")== 0)
     {
         printf("bye ");
     }
    }
  }

而不是strcmp使用strncmp strcmp將比較字符串中的所有字符,直到達到終止空字符或字符不同。 strncmp只會比較兩個字符串中的前 n 個值。 您還應該在printf("bye")之后添加break以離開循環。

#include <stdio.h>
#include <ctype.h>
#include<string.h>
int main (void)
{
    char *names;
    int capacity = 0;
    int size = 0;
    char name[100];

    printf ("Enter number 4 is you want to stop inputting names.\n");

    while (1)
    {
        printf ("Input:\n");
        fgets(name, sizeof(name),stdin);
        printf ("%s", name);

        if (strncmp(name, "end", 3)!= 0)
        {
            printf ("hello");
        }

        if (strncmp (name, "end", 3)== 0)
        {
            printf("bye ");
            break;
        }
    }
}

正如其他人已經提到的: fgets()存儲行尾字符\\n 如果您與"end\\n"進行比較,它將起作用。

暫無
暫無

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

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