如果輸入在字串名稱中,我想檢查輸入,然后列印給定名稱的編號。如果給定的名稱不在字串名稱中,則列印“你的名字不在此處”,但每次運行代碼時都會得到“你的名字不在此處”。
#include<stdio.h>
#include<cs50.h>
#include<string.h>
int main(void)
{
string userinput;
string names [] = {"david", "mark"};
string numbers[] = {"123456789","987654321"};
userinput = get_string("name: ");
for(int i = 0; i<2 ;i )
{
if(strcmp(names[i], userinput) == 0)
{
printf("your number is %s ", numbers[i]);
}
}
printf("your name is not here\n");
}
**ACTUAL OUTPUT**
name: david
your number is 123456789 your name is not here
uj5u.com熱心網友回復:
一個非常簡單的解決方案是創建一個變數來跟蹤是否找到名稱:
int found = 0;
for(int i = 0; i<2 ;i )
{
if(strcmp(names[i], userinput) == 0)
{
printf("your number is %s ", numbers[i]);
found = 1;
// Break so we don't have to iterate over the rest
// of the items if we already found our name.
break;
}
}
if (!found) printf("your name is not here\n");
uj5u.com熱心網友回復:
這自然是非常簡單的代碼,但你應該早就開始考慮程式設計了。你的代碼做了三個不同的、獨立的事情:
- 提示輸入/接受用戶輸入 (I/O)。
- 搜索輸入是否匹配一個值(搜索演算法)。
- 呈現結果 (I/O)。
理想情況下,將第 2) 部分和第 3) 部分分開,以免將 I/O 與演算法混淆,因此:
#include <stdbool.h>
...
bool found = false;
for(int i=0; i<2; i )
{
if(strcmp(names[i], userinput) == 0)
{
found = true;
break;
}
}
if(found)
{
printf("your number is %s \n", numbers[i]);
}
else
{
printf("your name is not here\n");
}
如果我們愿意,我們可以將這些部分拆分為單獨的函式。例如,如果字串的數量增加,我們將希望實作比這種“蠻力”回圈更好的搜索演算法。
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/437107.html
上一篇:c 中是否存在“elseif”或僅存在“if”和“else”?[復制]
下一篇:洗掉條件為R的重復項
