[英]Comparing user input to a predefined array of characters in C programming language
我有以下代碼,它應該作為命令獲取用戶輸入,然后檢查命令是否是預定義的。 但是,對於輸入的任何命令,輸出是“ 您要求幫助 ”。 我認為問題可能與我將用戶輸入字符串與設置字符串進行比較的方式有關,但我仍然需要幫助解決問題。
char command[10];
char set[10];
char set1[10];
strcpy(set, "help");
strcpy(set1, "thanks");
int a = 0;
while (a != 1)//the program should not terminate.
{
printf("Type command: ")
scanf("%s", command);
if (strcmp(set, command))
{
printf("You asked for help");
}
else if (strcmp(set1, command))
{
printf("You said thanks!");
}
else
{
printf("use either help or thanks command");
}
}
if (strcmp(set, command))
應該
if (strcmp(set, command) == 0)
原因是如果LHS或RHS較大, strcmp
返回非零值,如果它們相等則返回零。 由於零在條件中評估為“假”,因此您必須顯式添加== 0
測試,以使其在您期望的意義上成立,即相等。
首先,使用scanf()
時總是對輸入進行長度限制,例如
scanf("%9s", command);
對於10元素char
數組,以避免過長輸入導致緩沖區溢出。
也就是說, if...else
塊邏輯以下面的方式工作:
if (expression is true) { // produce a non-zero value, truthy
execute the if block
}
else { // expression is falsy
execute the else block
}
在您的情況下,控制表達式是strcmp(set, command)
。
現在,請注意,如果匹配 , strcmp()
返回0
,如果不匹配 ,則返回非零值。
從而,
0
- 將被評估為假,並且與您的期望相符,它將轉到else
部分。 if
塊將再次被錯誤地執行。 因此,在您的情況下,您需要更改條件以否定返回值,例如
if (!strcmp(set, command))
{
printf("You asked for help");
}
else if (!strcmp(set1, command))
{
printf("You said thanks!");
}
else
{
printf("use either help or thanks command");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.