c++ - 为什么我编译这段代码时会出现这个错误? (终止调用后~)

标签 c++ c++11

我正在解决以下算法问题
输入的第一行包含一个整数 N(1 ≤ N ≤ 1000),这是后面的数据集数。 每个数据集由一行输入组成,其中包含一个浮点( double )数、一个空格和要转换的测量单位规范。单位规范为 kg、lb、l 或 g 之一,分别表示千克、磅、升和加仑。

这是我的代码。
当我编译这段代码时,
'在抛出

的实例后终止调用

'std::out_of_range' what(): basic_string::erase: __pos (which is 18446744073709551615) > this->size() (which is 0)'

出现这个错误。我不知道为什么会出现这个错误。
我在 C++11 中使用 Dev C++ 和编译选项。

#include <iostream>
#include <cstring>
#include <sstream>
using namespace std;

string Convert(string data, int length);

int main()
{
int N;
cin>>N;
int temp(N);
string Ansarr[N];
int i=0;
while(temp>0){
    string A;
    cin>>A;
    int len=A.length();
    A=Convert(A,len);
    Ansarr[i++]=A;
}
i=0;
while(N>0){
    cout<<i+1<<' '<< Ansarr[i++]<<endl;
    }
}

string Convert(string data, int length)
{
string Result,unit;
double ConResult;
if(data.back()=='g'){
    if(data.at(length-2)=='k'){
        /*kg일때*/
        unit="lb";
        data.pop_back();
        data.pop_back();
        data.pop_back();
        double temp=stoi(data);
        ConResult=temp*2.2046;
    }
    else{
        /*g일때*/ 
        unit="l";
        data.pop_back();
        data.pop_back();
        double temp=stoi(data);
        ConResult=temp*0.4536;
    } 
}
else if(data.at(length-1)=='b'){
    /*lb일때*/ 
    unit="kg";
    data.pop_back();
    data.pop_back();
    double temp=stoi(data);
    ConResult=temp*0.2642;
} 
else{
    /*ㅣ일때*/ 
    unit="g";
    data.pop_back();
    data.pop_back();
    double temp=stoi(data);
    ConResult=temp*3.7854;
}
Result=to_string(ConResult);
Result.resize(6);
Result=Result+" "+unit;
return Result;
}

最佳答案

你不能这样做:

cout<<i+1<<' '<< Ansarr[i++]<<endl;
//    ^^^               ^^^

它有未定义的行为。编译器给出 warning在这一点上不要忽视它。编译器可以在这里自由地重新排序评估,所以你永远不知道哪个发生在另一个之后。


您需要对您使用的每个 at 进行范围检查。 请注意,如果 length 由于溢出而为 0,则 length-1 可能是一个非常大的数字。因为 at 接受一个 size_t。这是一个示例检查。

if (data.length() >= 2)
   data.at(data.length() - 2);

可变长度数组不是 ISO C++:

string Ansarr[N];

您可以改用 std::vector:

std:: vector<std:: string> Ansarr(N);

关于c++ - 为什么我编译这段代码时会出现这个错误? (终止调用后~),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58586295/

相关文章:

c++ - 如果 gdb frams/bt 显示 "??"但没有 readalbe 函数名称,会发生什么情况?

c++ - 为什么我的 NamedPipe 用空格分隔我的字符串?

c++ - 使用 Curiously Recurring Template Pattern 时如何实例化基类?

c++ - 错误 “no matching function for call ' begin(int [len] )' ”在我的代码中是什么意思?

c++ - 信号槽的语法糖

c++ - std::bind 重载决议

c++ - 在 C++ 中获取 mp3 长度

c++ - 增强现实 : Render Video on top of a marker

c++ - "this"指针上的指针运算

c++ - 为什么需要使用 unordered_map 和元组的默认构造函数?