dimanche 27 octobre 2019

Why this error happens when I compile this code? (terminate called after~)

I am solving the following alogrithm problem
The first line of input contains a single integer N, (1 ≤ N ≤ 1000) which is the number of datasets that follow. Each dataset consists of a single line of input containing a floating point (double precision) number, a space and the unit specification for the measurement to be converted. The unit specification is one of kg, lb, l, or g referring to kilograms, pounds, liters and gallons respectively.

And here is my code.
When I compile this code,
'terminate called after throwing an instance of 'std::out_of_range' what(): basic_string::erase: __pos (which is 18446744073709551615) > this->size() (which is 0)'
this error appears. I have no idea why this error appears.
I use Dev c++ and compile option in c++11.

#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;
}

Aucun commentaire:

Enregistrer un commentaire