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

C++中string.size()判断异常导致错误输出问题求助

问题分析与修复方案

核心问题原因

你的代码里用rand() % 27生成随机索引,但字母表alphabet只有26个小写字母(索引范围0-25)。当随机值取到26时,会访问字符串末尾的终止符\0(ASCII空字符)。把这个空字符拼接到word后,word的实际长度确实是2,但cout输出时遇到\0就会停止打印,导致你看到的是单字符内容,而程序判定长度为2,触发了输出逻辑。

修复步骤

  1. 修正随机索引范围:将取模值从27改为26,确保只访问字母表的有效字符:
    int randomIndex = rand() % 26;
    
  2. 规范头文件引用:原代码包含的<string.h>是C语言字符串处理头,C++中使用std::string应该包含<string>头(部分编译器兼容,但这是规范写法)。
  3. 优化计数逻辑(可选):当前i仅在生成错误单词时递增,成功生成"hi"时不会计数。如果需要统计总尝试次数,把i += 1;移到if (word.size() == 2)块的末尾,不管成功失败都执行。

修复后的完整代码

#include <iostream>
#include <time.h>
#include <string>

int main()
{
    std::string alphabet = "abcdefghijklmnopqrstuvwxyz";
    std::string word;

    unsigned long long int i = 0;
    srand(time(NULL));
    while(true)
    {
        int randomIndex = rand() % 26;
        word += alphabet[randomIndex];

        if (word.size() == 2) 
        {
            std::cout << i << " : " << word << " (长度:" << word.size() << ")" <<  std::endl;
            if (word == "hi") 
            {
                break;
            }
            else 
            {
                word = "";
            }
            i += 1;
        }
    }
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.20 10:31:19