簡體   English   中英

簡單的 C 程序不返回任何輸出

[英]Simple C program returns no output

我編寫了一個簡單的 C 程序,它接受用戶輸入並將其存儲在 dataofUser 變量中,然后它允許用戶選擇是否要通過說是或否來顯示他們輸入的數據,這是通過 fgets 和 if 語句完成的檢查 userChoice 變量是否在其中存儲了 yes 或 no 取決於它是或否,它將顯示數據或顯示“無輸出!”,當我運行程序時,我沒有得到我在下面輸入的數據的輸出,你可以看到控制台上顯示的內容:

Please enter your input: this is a random input
Your data has been entered please enter Yes or No to display it: yes

Process returned 0 (0x0)    execution time : 4.829 s
Press ENTER to continue.

這是構建消息日志和各種錯誤消息

||=== Build: Debug in randopoint2 (compiler: GNU GCC Compiler) ===|
/home/Documents/randopoint2/randopoint2/main.c||In function ‘main’:|
/home/Documents/randopoint2/randopoint2/main.c|17|warning: comparison between pointer and integer|
/home/Documents/randopoint2/randopoint2/main.c|17|warning: comparison with string literal results in unspecified behavior [-Waddress]|
/home/Documents/randopoint2/randopoint2/main.c|21|warning: comparison between pointer and integer|
/home/Documents/randopoint2/randopoint2/main.c|21|warning: comparison with string literal results in unspecified behavior [-Waddress]|
||=== Build finished: 0 error(s), 4 warning(s) (0 minute(s), 0 second(s)) ===|
||=== Run: Debug in randopoint2 (compiler: GNU GCC Compiler) ===|

#include <stdio.h>
#include <stdlib.h>

int main()
{
    char dataOfUser[50];
   char userChoice[50];

  printf("Please enter your input: ");
  fgets(dataOfUser, 50, stdin);

  printf("Your data has been entered please enter Yes or No to dipslay it: ");
  fgets(userChoice, 50, stdin);


  if(userChoice[50] == "yes")
  {
  printf("Your notes are: %s", dataOfUser);
  }
  else if(userChoice[50] == "no")
  {
  printf("no output!");
  }

    return 0;
}

問題:

if(userChoice[50] == "yes")

這不是在 C 中比較字符串的方式。

此外,訪問userChoice[50]是未定義的行為,因為您試圖訪問數組超出其范圍。

else if(userChoice[50] == "no")

另請注意,當您按 Enter 結束輸入時,換行符\\n存儲在userChoice

解決方案:

  1. 添加#include <string.h>以獲取strcmp函數。

  2. if(userChoice[50] == "yes")更改為if (strcmp(userChoice, "yes\\n") == 0)

  3. else if(userChoice[50] == "no")改為else if (strcmp(userChoice, "no\\n") == 0)

在旁邊:

printf("Your data has been entered please enter Yes or No to dipslay it: ");

您要求用戶輸入“是”或“否”,但將其與代碼中的“是”和“否”進行比較。

暫無
暫無

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

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