如何在不循环打印 "error" 消息的情况下 运行

How do I run this without the loop printing the "error" message

所以我对编码很陌生(几天前才真正开始学习 c),所以我决定随便玩玩,看看我是否可以应用到目前为止所学的知识。我创建了一个 "employee search" 程序,提示用户输入姓名,它会检查该员工是否存在。我运行进入循环内的一个问题;如果我在终端中输入 "Chris" 并点击回车,它会说类似这样的话: "Employee not found." "Chris found." "Employee not found."How do I go about making the program confirm the name在 "database" 内,而不会重复 "error" 消息。对不起,新手问题。同样,我对此很陌生。

#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");

        }
    }
}

避免在循环内打印。而是使用标志来保存状态。喜欢:

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");
}
#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");     
}
 // 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"}