用C++实现:有一个单词管理类,能存放10个单词,有10个单词存放在二维指针数组words中。编写一个程序,(1)根据用户的输入找出所有从首字母开始与之从前向后匹配的单词(包含即可),并最后输出个数,如果没有包含匹配的,只需输出0;(2)输入编号1-10,输出对应的单词。
时间: 2023-05-22 10:03:29 浏览: 42
以下是程序代码:
#include <stdio.h>
#include <string.h>
#define WORDS_NUM 10
#define WORDS_LENGTH 20
char* words[WORDS_NUM] = {"hello", "world", "this", "is", "a", "test", "program", "for", "CSDN", "chatbot"};
void searchWord(char* input)
{
int count = 0;
for (int i = 0; i < WORDS_NUM; i++)
{
if (strncmp(input, words[i], strlen(input)) == 0)
{
printf("%s\n", words[i]);
count++;
}
}
if (count == 0)
{
printf("0\n");
}
else
{
printf("total: %d\n", count);
}
}
void getWord(int index)
{
if (index < 1 || index > WORDS_NUM)
{
printf("invalid index\n");
}
else
{
printf("%s\n", words[index-1]);
}
}
int main()
{
char input[WORDS_LENGTH];
printf("please input a word: ");
scanf("%s", input);
searchWord(input);
int index;
printf("please input a number (1-10): ");
scanf("%d", &index);
getWord(index);
return 0;
}
如果输入 "t",则输出:
this
test
total: 2
please input a number (1-10):
如果输入 "8",则输出:
for
please input a number (1-10):
希望回答能够帮助到您。