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

C++如何提取大括号包裹的子字符串?代码运行无输出如何排查?

问题排查
  • 输入读取逻辑错误:cin >> funct 遇到空格会终止读取,输入text{hello world}时只会读取到text{hello,无法拿到完整字符串,应替换为getline(cin, funct)读取整行内容。
  • temp变量逻辑完全错误:初始值为0,执行temp += temp后值永远为0,不仅无法向后遍历字符串,还会导致死循环。
  • 字符拼接逻辑错误:每次给word赋值单个字符会覆盖之前的内容,最终只能得到单个字符,应该用追加方式拼接字符串。
  • 大括号定位逻辑缺失:找到text关键词后没有先定位到左大括号{的位置,直接从偏移5的位置取字符逻辑完全不可靠,应该先找到{的下标,再从下一位开始遍历到}为止。
  • 边界校验缺失:没有判断字符串中是否存在{和},直接调用at()方法如果下标越界会直接抛出异常终止程序。
修复后代码
#include <iostream>
#include <string>

using namespace std;

int main(){
    start:    
    std::string funct;
    
    std::cout << "-->";
    // 读取整行输入,支持带空格的内容
    getline(cin, funct);
    
    string word;
    size_t text_pos = funct.find("text");
    if (text_pos != string::npos)
    {
        // 定位左大括号位置
        size_t left_brace = funct.find('{', text_pos);
        size_t right_brace = funct.find('}', left_brace);
        if (left_brace != string::npos && right_brace != string::npos) {
            // 截取两个大括号中间的内容
            word = funct.substr(left_brace + 1, right_brace - left_brace - 1);
            cout << word << endl;
        }
    }
    
    cout << endl << endl << "==================================================" << endl << endl;
    goto start;
    
    return 0;
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 03:09:03