程序崩溃并显示"std::out_of_range"错误

Program crashing with 'std::out_of_range' error

本文关键字:of 错误 range out std 崩溃 显示 程序      更新时间:2023-10-16

我正在为学校做一个命运之轮项目,遇到了一些指针问题。

这是我在程序中遇到的问题,(cmd输出(:

terminate called after throwing an instance of 'std::out_of_range'
what():  basic_string::compare: __pos (which is 1) > this->size() (which is 0)
This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.

该游戏的设计与命运之轮游戏类似。我首先要做的是过滤掉"rlstne"字母。这在不使用指针的情况下有效,但我必须使用指针。这是我的完整程序:

#include <iostream>
#include <stdio.h>
#include <string.h>
#include <ctype.h>
#include <cctype>
#include <time.h>
#include <Windows.h>
int main(){
std::string original_string = "THIS LINE IS THE GAME";
std::string str1;
std::string str2 = "RLSTNE";
int y = 0;
bool restart = true;
std::string* arr_temp =  new std::string[100];
std::string* arr_temp1 = new std::string[100];
*arr_temp1 = str1;
*arr_temp = str2;
do{
std::cout << "What string?" << std::endl;
getline(std::cin, str1);
std::cout << str1.length() << std::endl;
for(int x = 0; x < str1.length(); x++){
if((arr_temp->compare(0,1, *arr_temp1, x, 1)) == 0){
str1[x] = '_';
}
if((arr_temp->compare(1,1, *arr_temp1, x, 1)) == 0){
str1[x] = '_';
}
if((arr_temp->compare(2,1, *arr_temp1, x, 1)) == 0){
str1[x] = '_';
}
if((arr_temp->compare(3,1, *arr_temp1, x, 1)) == 0){
str1[x] = '_';
}   
if((arr_temp->compare(4,1, *arr_temp1, x, 1)) == 0){
str1[x] = '_';
}
if((arr_temp->compare(5,1, *arr_temp1, x, 1)) == 0){
str1[x] = '_';
}
}
*arr_temp1 = str1;
std::cout << *arr_temp1 <<std::endl;
Sleep(1000);
}while(restart);
}

我想这就是我的程序出错的地方:

std::string str1;
std::string str2 = "RLSTNE";

str1没有初始化为任何值,所以编译器将其视为0长度,但我尝试将其初始化为不同的值。例如original_string的字符串值。

这是代码:

std::string str1 = "THIS LINE IS THE GAME";
std::string str2 = "RLSTNE";

这是输出:

What string?
THIS LINE IS THE GAME
21
_HI_ _I__ I_ _H_ GAM_

但当我试图添加比原始值21更多的值时,我会遇到这个问题:

What string?
THIS LINE IS THE GAMEEEE
24
terminate called after throwing an instance of 'std::out_of_range'
what():  basic_string::compare: __pos (which is 22) > this->size() (which is 21)

所以我的问题是:编译器打印出来的是什么?什么值是22,什么值是21?这个->尺寸是什么意思?__pos是什么意思?

提前谢谢。

std::string* arr_temp =  new std::string[100];
std::string* arr_temp1 = new std::string[100];

每一个都是指向100个字符串数组的指针。此外,因为您使用new,所以您需要在代码中的某个位置使用delete,否则就会出现内存泄漏。但你似乎不需要动态记忆。所以固定版本是

std::string* arr_temp;
std::string* arr_temp1;

您的大for循环可以通过嵌套循环来简化,但这并不是真正的重点。至于您的错误-异常std::out_of_range意味着您超出了数组的限制。导致它的代码如下:

std::string str1 = "THIS LINE IS THE GAME"; //makes a new string
*arr_temp1 = str1; //dereferences arr_temp1 and sets arr_temp1[0] to whatever str1 currently is

所以您已经设置了arr_temp1[0] = "THIS LINE IS THE GAME"(长度为21(。然后设置str1 = "THIS LINE IS THE GAMEEEE"(长度为24(。循环尝试访问arr_temp1[0]的前24个字符。但这行不通——它的长度是21。因此,一旦到达第22个字符,它就会抛出一个std::out_of_range错误。

总之,大多数都不是你想的那样。我建议你多读一些指针,然后从头开始。