[英]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.