【发布时间】:2017-11-25 07:24:19
【问题描述】:
所以我对编码非常陌生(实际上是几天前开始学习 c),我决定只是玩玩,看看我是否可以应用我目前学到的东西。我创建了一个“员工搜索”程序,它会提示用户输入姓名,它会检查员工是否存在。我在循环中遇到了一个问题;如果我在终端中输入“Chris”并点击回车,它会显示类似:“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");
}
}
}
【问题讨论】:
-
found."行在做什么?这是C,即string是什么? -
也许在 cs50.stackexchange.com 上问这个
-
通过在循环中设置标志并随后报告。而不是每次迭代都报告。
-
... 甚至更好,您也许可以在 cs50.stackexchange.com 上轻松找到 answer 而无需询问
-
这完全取决于未知的
get_string();函数是否包含行终止 字符。这也是Is it a good idea to typedef pointers?是否的一个很好的例子。 (显然发生在cs50.h)