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

C++与SplashKit实现数组值索引定位函数的运行异常排查

姓名查找功能的代码问题定位与修正

核心错误清单

  • 未实际调用查找函数:main函数末尾的int index_of(int value, string names[], int size); 是函数声明语句,不是函数调用,程序运行到此处不会执行任何查找逻辑,既不会弹出待查找姓名的输入提示,也不会触发数组匹配流程。
  • 代码执行顺序逻辑倒置:在index_of函数的匹配分支中,return i语句写在了打印索引的代码之前。程序执行到return会直接终止函数运行,后续的write_line("The index is: ");、write(i)属于无执行机会的死代码,就算成功匹配到姓名,用户也看不到对应索引输出。
  • 参数定义冗余且类型不匹配:
    • 函数内部已经通过read_string获取待查找的姓名,入参设计的value完全没有实际作用,属于冗余参数
    • main函数内嵌套声明的函数,把本该为string类型的待查找值参数写成了int类型,就算后续替换为实际调用语句,也会出现类型不兼容的运行异常
  • 边界场景无反馈:数组遍历完成未匹配到目标时,函数返回-1后没有配套的用户提示,用户无法感知查找失败的结果
  • 字符串比较存在兼容隐患:当前匹配判断里的if ((names[i]) == string(value)) 写法,在SplashKit的string封装下会存在不必要的类型转换,可能因为字符串封装差异导致匹配判断失效,直接用两个string变量做相等比较即可完成正确判断。

修正后的可运行代码

修正后的index_of函数(去掉冗余入参、调整执行顺序、修正比较逻辑、增加未找到的提示):

int index_of(string names[], int size)
{
    string target = read_string("Enter name to find index: ");
    
    for(int i = 0; i < size; i++)
    {
        if(names[i] == target)
        {
            write_line("The index is: ");
            write_line(i);
            return i;
        }
    }
    write_line("Matching name not found");
    return -1;
}

修正后的main函数部分(替换原来的函数声明为实际调用,接住返回值):

int main()
{
    #define SIZE 5
    string names[SIZE];
    int i;

    i = 0;
    while( i < SIZE )
    {
        names[i] = read_string("Enter a name:");
        i++;
    }

    for(i = 0; i < SIZE; i++)
    {
        write_line(names[i]);
    }

    int total;
    total = total_length(names, SIZE);

    write("Total length: ");
    write_line(total);

    bool has_connor;
    has_connor = contains(names, SIZE, "connor");

    if ( has_connor ) write_line("contains Connor");
    
    write("The longest name is: ");
    write_line(longest_name(names, SIZE));

    // 实际调用查找函数
    int found_index = index_of(names, SIZE);
    write("Search result code: ");
    write_line(found_index);

    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.24 02:36:04