jeudi 19 novembre 2020

std::to_string keeps throwing std::out_of_range error

I have the following code that keeps giving me errors when I try to run it, more exactly std::out_of_range. I tried everything and nothing works. I think I am making a mistake and I can't see it.

#include <iostream>
#include <fstream>
#include <string>

using namespace std;

string fc_md(string input)
{
    string result = input;
    size_t coord1 = -1, coord2 = -1;
    for (unsigned int i = 0; i <= result.length(); i++)
    {
        if (input[i] == 42)
        {
            coord1 = coord2;
            coord2 = i;
            long long b = stoll(result.substr(coord1 + 1, result.length()), &coord2), a = stoll(result.substr(coord1 + 1, coord2 - 1));
            result.erase(coord1 + 1, coord2);
            result.insert(coord1, to_string(a + b));
        }
        else
        {
            if (input[i] == 47)
            {
                coord1 = coord2;
                coord2 = i;
                long long res = stoll(result.substr(coord1 + 1, coord2 - 1)) / stoll(result.substr(coord1 + 1, result.length()), &coord2);
                result.erase(coord1 + 1, coord2);
                result.insert(coord1+1, to_string(res));
            }
            else
            {
                if (input[i] < 48 && input[i]>57 && input[i] != 46)
                {
                    coord1 = coord2;
                    coord2 = i;
                }
            }
        }
    }
    return result;
}

int main()
{
    string input;
    cin >> input;
    cout << fc_md(input);
}

Aucun commentaire:

Enregistrer un commentaire