所以我对编码非常陌生(几天前从字面上开始学习c),我决定到处玩,看看我是否能应用到目前为止学到的东西。我创建了一个“员工搜索”程序,提示用户输入名称,然后检查员工是否存在。我在循环中遇到了一个问题;如果我在终端输入“Chris”并点击回车,它会说:“找不到员工”。 “克里斯发现了。” “未找到员工。”如何使程序确认名称在“数据库”中,而不重复“错误”消息。对不起新手问题。我再次对此非常陌生。
#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 :(得分: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 :(得分: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");
}
答案 2 :(得分:-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"}