执行完所有if else代码后如何打印最后一个条件
我想检查输入是否在字符串名称中,然后打印 给定的名称。如果给定的名称不在字符串名称中,则打印“您的名字不在这里”,但每次运行代码时我都会收到“您的名字不在这里”。
#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
I want to check the input if the input is in the string names then print the number of the
given name. If the given name is not in the string names then print "your name is not here" but I'm getting "your name is not here" every time I run my code.
#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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
一个非常简单的解决方案是创建一个变量来跟踪名称是否已找到:
A very simple solution would be creating a variable to keep track if the name has been found:
这自然是非常简单的代码,但是您应该尽早开始考虑程序设计。您的代码执行三件不同的、独立的事情:
理想情况下,将第 2) 部分和第 3) 部分分开,以免将 I/O 与算法混淆,因此:
如果我们愿意,我们可以将这些部分拆分为单独的函数。例如,如果字符串数量扩大,我们将希望实现比这种“暴力”循环更好的搜索算法。
This is naturally very simple code, but you should already start to think about program design early on. Your code does three different, separate things:
Ideally keep parts 2) and 3) separate not to mix up I/O with algorithms, so:
We could split up these parts in separate functions if we wish. For example if the amount of strings is expanded, we'll want to implement a better search algorithm than this "brute force" loop.