繁体   English   中英

抛出'std :: out_of_range'what():basic_string :: insert实例后,c ++终止调用

[英]c++ terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::insert

程序旨在用户输入一个字符串,例如“ TheDogIsHappy”,然后显示该字符串,并在大写单词之间留一个空格。 程序仅用两个单词就可以正常工作,但是当字符串中包含多个单词时:运行程序时收到此错误:抛出'std :: out_of_range'what()实例之后终止调用what():basic_string :: insert不要看到字符串超出边界的任何地方,因为它只会循环到字符串的长度,所以不知道为什么会出现超出范围的错误。

#include <cstdlib>
#include <iostream>
#include <string>
#include <cctype>
#include <stdio.h>
#include <ctype.h>

using namespace std;

int main(int argc, char *argv[])
{
    string string1 = "";
    string string2 = "";
    int n;
    double length1;
    cout << "Enter String: " << endl;
    cin >> string1;
    n = 1;
    length1 = string1.length();
    for (int i = 0; i <= string1.length();i++) { 
        if (isupper(string1[n])) {
        string1.insert(n," ");
        n = n + 1;
        }
        n = n + 1;   
    }
    cout << "String is: ";
    n = 0;
    for (int i = 0; i <= string1.length();i++) { 
        cout << string1[n]; 
        n = n + 1;
        }
    cout << endl;
    cout << "Press the enter key to continue ...";
    string s;
    cin >> s;
    return EXIT_SUCCESS;
}

您需要使用< string1.length()因为索引从0开始,因此实际长度的值不是字符串中的有效索引。

如果尝试访问stringlength ,则将超出该范围。 就像在array[5]访问大小为5的array[5] 最后一个位置是array[4]

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM