You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C++查找输入最短单词时报no match operator错误是什么原因?

错误原因

  • 触发no match operator报错的核心是:你当前对比的两个操作数类型不匹配,word[i]是std::string类型,len是未初始化的int类型,C++没有默认实现string和int直接用<比较的运算符重载。
  • 除此之外你的代码还有多处逻辑问题:
    1. 初始化min时调用了word[SZ].length(),数组下标从0开始,SZ值为5,word[SZ]属于数组越界访问,会触发未定义行为。
    2. 变量len从声明到使用全程没有赋值,属于未初始化变量直接使用。
    3. min的类型你声明为int,但循环内试图给min赋值word[i](string类型),类型不匹配。
    4. 没有引入<string>头文件就使用std::string,属于不规范写法,部分编译器会直接报错。

修正后的可运行代码

#include <iostream>
#include <string>
using namespace std;

int main () {
    const int SZ = 5;
    string word[SZ];
    // 录入5个单词
    for(int i = 0; i < SZ; i++){
         cout << "请输入第" << i+1 << "个单词: ";
         cin >> word[i];
    }
    // 初始化最短单词、最短长度为第一个元素的对应值
    string shortest_word = word[0];
    int min_len = word[0].length();
    // 遍历对比长度
    for(int i = 1; i < SZ; i++){
        int current_len = word[i].length();
        if(current_len < min_len){ 
            min_len = current_len;
            shortest_word = word[i];
        }
    }
    cout << "最短的单词是:" << shortest_word << ",长度为:" << min_len << endl;
    return 0;
}

内容的提问来源于stack exchange,提问作者JohnIsStupid

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.09.29 03:36:08