2017-11-25 10 views
-4

私は非常にコーディングに新しいです(文字通り数日前に学習を始めました)、私は周りを遊んで、遠いユーザーに名前を入力する「従業員検索」プログラムを作成し、その従業員が存在するかどうかを確認します。私はループの中で問題に遭遇した。ターミナルに「Chris」と入力して「enter」をクリックすると、「Employee not found」のように表示されます。 "クリスが見つかりました。" 「従業員が見つかりませんでした。」「エラー」メッセージを繰り返さずに、名前が「データベース」内にあることをプログラムに確認させるにはどうすればよいですか。初心者の質問には申し訳ありません。繰り返しますが、私はこれについて非常に新しいです。"エラー"メッセージを印刷しないでこれを実行するには

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

int main(void) 
{ 
    // declare array 
    string employee[] = {"Damien", "Chris", "Emma"}; 

    // print intro message and prompt user for name 
    printf("Welcome to employee search\n"); 
    printf("Please input an employee name: "); 
    string name = get_string(); 

    // here is where I run into the issue where it'll repeat "employee not found" 
    for(int i = 0; i < 3; i++) 
    { 
     if(strcmp(name, employee[i])==0) 
     { 
      printf("%s found\n", name); 
     } 
     else 
     { 
      printf("Employee not found\n"); 

     } 
    } 
} 
+0

は、ライン '見つかった" '何をしているか、このCすなわち' STRING'何です –

+2

は、おそらく設定することでcs50.stackexchange.com –

+0

でこれを頼みます?ループ内のフラグとそれ以降の報告各反復について報告するのではなく –

答えて

2

ループ内での印刷は避けてください。代わりにフラグを使用してステータスを保存します。以下のように:。?

int flag = 0; // Initialize flag to 0 (i.e. assume the name isn't found) 

for(int i = 0; i < 3; i++) 
{ 
    if(strcmp(name, employee[i])==0) 
    { 
     flag = 1; // Set flag to 1 to remember that we had a match 

     break;  // Stop the loop using break. We don't need to check the rest 
        // as we have found a hit 
    } 
} 

if (flag) 
{ 
    printf("%s found\n", name); 
} 
else 
{ 
    printf("Employee not found\n"); 
} 
1
#include <cs50.h> 
#include <stdio.h> 
#include <string.h> 

int main(void) 
{ 
    string employee[] = {"Damien", "Chris", "Emma"}; 
    int i = 0; 

// print intro message and prompt user for name 
printf("Welcome to employee search\n"); 
printf("Please input an employee name: "); 
string name = get_string();  //Declaration and initialisation 

for(i = 0; i < 3; i++) 
{ 
    if(strcmp(name, employee[i])==0) 
    { 
     printf("%s found\n", name); 
     break; // if any of the employee is found it exit the loop immediately with the value of i<3 
    } 

} 
if (i ==3) //means the loop has reached end without finding any of employee. 
     printf("Employee not found\n");  
} 
+0

おそらくコードを適切にフォーマットして、説明文を追加してください。 –

+0

説明が追加されました。それはyewを助けることを願っています –

+1

'i'は' for'ループの外にあります。 –

-2
// yes dear it a bit easy 
// first get the input in any variable 
    string name=""; 
// And then inside a loop chek every index of array to the string which you get from the user 

cout<<" Enter name "; 
cin>>name; 

for(int i=0; i<=c.length;i++) 
{ if(c[i]==name) 
    { 
    cout<<"found"; 
    } 
else{ cout<<"not found "; 
    } 

} 

// c just like c={"first name","secound_name","blablala"} 
+0

おそらくコードを適切に書式設定して説明を追加してください –

+1

質問にタグがありませんC++ではない –

+0

このコードでは質問に対する回答は得られません。 – alk

関連する問題