Java教程

名字匹配否?

本文主要是介绍名字匹配否?,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
写一个程序提示用户输入姓名,然后在一个保存在数组中的名字列表中查找该姓名,如果找到则显示适当的欢迎信息,否则显示“名字没有找到”。
名字列表为:{"abc", "bbc", "ccc", "Hello", "John", "Tome"};

**提示信息:"请输入一行字符:"
**输出格式要求:"欢迎你,%s!"  "名字没有找到!"

法一:指针

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

int main()
{	 	       
    char *namedb[] = {"abc", "bbc", "ccc", "Hello", "John", "Tome"};
    char name[100];
    int i;

    printf("请输入一行字符:");
    gets(name);

    for (i = 0; i < 6; i++)
    {	 	       
        if (!strcmp(name, namedb[i]))
        {	 	       
            printf("欢迎你,%s!", name);
            exit(0);
        }
    }
    printf("名字没有找到!");

    return 0;
}

法二:

#include<iostream>
#include<string>
using namespace std;
int main(void)
{
    string input;
    string names[10] = {"abc", "bbc", "ccc", "Hello", "John", "Tome"};
    cout << "Please input your name : ";		
    cin >> input;
    
    int i, flag = 0;
    for (i = 0; i < 10; i++)
    {
        if (names[i] == input)
        {
            flag = 1;
            break;
        }
    }
    
    if (flag == 1)
    {
        cout << "Hello," << input << '!' << endl;
    }
    else
    {
        cout << "Name are not found.";
    }
}

如有疏漏,还请各位大佬多多指教

【玩儿】Harry Potter

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

int main()
{	 	       
    char *namedb[] = {"Harry James Potter", "Ron Billius Weasley", 
                      "Hermione Jane Granger", "Albus Percival Wulfric Brian Dumbledore", 
                      "Minerva Mcgonagall", "Severus Snape","Remus John Lupin", 
                      "Tom Marvolo Riddle", "Rubeus Hagridv", "Voldemort", 
                      "Sirius Black", "Filch", "Ginny Weasley", "Cho Chang"};
    char name[100];
    int i;

    printf("Please input a name that you have heard in Harry Potter:");
    gets(name);

    for (i = 0; i < 22; i++)
    {	 	       
        if (!strcmp(name, namedb[i]))
        {	 	       
            printf("Hello,%s!", name);
            exit(0);
        }
    }
    printf("Name are not found.");

    return 0;
}

这篇关于名字匹配否?的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!