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

C++程序报std::out_of_range错误,打字机循环实现求助

解决C++打字机功能中的std::out_of_range错误

你遇到的terminate called after throwing an instance of 'std::out_of_range' error错误,是字符串操作索引越界导致的,具体问题出在这几点:

  1. 索引范围错误:std::string的索引从0开始,有效范围是0 <= 索引 < 字符串长度。你的循环条件while (t<=i)会让t最终等于原字符串长度i,此时调用testo.erase(i)必然越界——原字符串的最大有效索引是i-1。
  2. 忽略字符串长度动态变化:每次调用testo.erase(t)都会缩短字符串长度,但t仍按照原字符串长度i递增,后续t会远大于当前字符串的实际长度,进一步触发越界。
  3. 逻辑与需求偏差:你的代码通过删除字符来显示内容,和打字机“逐步显示字符”的需求相反,反而容易引发问题。

修正后的打字机代码

推荐用逐步拼接字符的方式实现,逻辑更直观,也能避免越界问题:

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

void typewriter(const std::string& testo, int tempo) {
    std::string displayed_text;
    for (char c : testo) {
        system("CLS");
        displayed_text += c;
        std::cout << displayed_text << std::flush; // 强制刷新输出缓冲区,确保立刻显示
        Sleep(tempo);
    }
}

若坚持原删除思路的修正方案

如果想保留“从完整字符串逐步缩短显示”的逻辑,需调整索引和循环条件避免越界:

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

void typewriter(std::string testo, int tempo) {
    int len = testo.length();
    while (len > 0) {
        system("CLS");
        std::cout << testo << std::flush;
        Sleep(tempo);
        testo.erase(testo.end() - 1); // 删除最后一个字符
        len--;
    }
}

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.15 06:25:19