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

C++ std::string的find()方法判断数字含8仅开头生效异常如何解决?

问题排查与修复

问题根源

你的代码判断逻辑存在错误:

  • std::string的find()方法查找不到目标子串时,返回的是std::string::npos(size_t类型的最大值),而非size_t()初始化得到的0值。你拿查找结果和0比对,逻辑完全不符合需求。
  • 额外调用rfind()做判断完全多余,只要find()返回值不是std::string::npos,就可以证明字符串包含字符'8'。

修正后代码

#include <iostream>
#include <string>

using namespace std;

unsigned long long g = 0;

int main()
{
    string str;
    cin >> str;
    int f = stoi(str);
    const string eig = "8";
    for (int a = 1; a <= f; a++)
    {
        string b = to_string(a);
        // 仅需判断find返回值不是npos即可
        if (b.find(eig) != string::npos)
        {
            cout << "It worked with " << b << "\n";
            g++;
        }
        
    }
    cout << g;
    return 0;
}

可选优化

如果输入数值范围较大,可不用转字符串,直接通过算术运算逐位判断,性能更高:

bool containsEight(int num) {
    while(num > 0) {
        if(num % 10 == 8) return true;
        num /= 10;
    }
    return false;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.30 06:27:03