c++实现人机成语接龙

        以下是用C++实现的人机成语接龙:

#include <iostream>
#include <string>
#include <vector>
#include <cstdlib>
#include <ctime>
using namespace std;

vector<string> idioms{"金蝉脱壳", "百里挑一", "金玉满堂", "背水一战", "霸王别姬", "天上人间", "不吐不快", "海阔天空", "情非得已", "滴水不漏"};

bool isLegal(const string& lastWord, const string& newWord) // 判断新成语是否合法
{
    if (newWord.empty()) return false;
    if (lastWord.empty()) return true;
    if (lastWord.back() != newWord.front()) return false;
    for (const auto& idiom : idioms)
    {
        if (idiom == newWord) return false;
    }
    return true;
}

string generateWord(const string& lastWord) // 生成新成语
{
    srand(static_cast<unsigned int>(time(nullptr)));
    vector<string> temp;
    for (const auto& idiom : idioms)
    {
        if (lastWord.empty() || lastWord.back() == idiom.front()) temp.push_back(idiom);
    }
    if (temp.empty()) return "";
    return temp[rand() % temp.size()];
}

int main()
{
    string lastWord;
    while (true)
    {
        cout << "请输入成语(不要带句号):";
        string newWord;
        getline(cin, newWord);
        if (!isLegal(lastWord, newWord))
        {
            cout << "你输错了,请重新输入!" << endl;
            continue;
        }
        lastWord = newWord;
        cout << "计算机回答:" << generateWord(lastWord) << endl;
    }
    return 0;
}

        此程序使用了vector存储成语库,通过isLegal函数判断新成语是否合法,通过generateWord函数生成新成语。主函数中不断循环读入用户输入的成语,并调用以上两个函数进行判断和生成新成语。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Galaxy银河

你的鼓励是我的动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值