解析不起作用:抛出 "std::invalid argument" 的实例后调用终止

Parsing does not work: terminate called after throwing an instance of "std::invalid argument"

我想要一个函数,它 return 是一个包含 2 个整数的向量。输入是一个字符串。

插入的字符串的布局应始终如下所示:“COORDINATES 123 456”,坐标为任意长度的整数。

如果字符串是“COORDINATES 123”或“COORDINATES 123 456 789”,函数应该return一个空向量。

#include <iostream>
#include <string>
#include <vector>

std::vector<int> getCoordinates(std::string string){
    auto count = 0;
    std::string coordinates;
    int coordinatesInt;
    std::vector<int> vector;
    int i, j = 0;
    for(int i = 0; i < string.size(); i++){
        if(string.at(i) == ' '){
            count++;
            j = 1;
            while(string.at(i+j) != ' ' && string.at(i+j) <= string.length()){
                coordinates.push_back(string.at(i+j));
                j++;
            }
            coordinatesInt = std::stoi(coordinates);
            vector.push_back(coordinatesInt);
        }
    }
    if(count != 2){
        vector.clear();
    }
    std::cout << count << std::endl;
    return vector;
}


int main()
{
    std::string coordinates = "COORDINATES 123 456";
    std::vector<int> vectorWithCoordinates = getCoordinates(coordinates);
    std::cout << vectorWithCoordinates[1] << std::endl;
    //vectorWithCoordinates should now contain {123, 456}
    return 0;
}

但是,当我 运行 这段代码时,我收到一条错误消息:

terminate called after throwing an instance of "std::invalid argument"
#include <iostream>
#include <string>
#include <vector>

std::vector<int> getCoordinates(std::string string){
auto count = 0;
std::string coordinates;
int coordinatesInt;
std::vector<int> vector;
for(unsigned i = 0; i < string.size(); i++){
    if(string.at(i) == ' '){
        count++;
        unsigned j = 1;
        while(i+j<string.size() && string.at(i+j) != ' '){ //checks that you do not go out of range before checking the content of the string
            coordinates.push_back(string.at(i+j));
            j++;
        }
        coordinatesInt = std::stoi(coordinates);
        vector.push_back(coordinatesInt);
    }
    coordinates.clear();//clears the string in order to have two different integers
    }
    if(count != 2){
       vector.clear();
    }
    std::cout << count << std::endl;
    return vector;
}


int main()
{
 std::string coordinates = "COORDINATES 123 456";
 std::vector<int> vectorWithCoordinates = getCoordinates(coordinates);
 for(auto i : vectorWithCoordinates)
 std::cout<<i<<"\n";
 //vectorWithCoordinates should now contain {123, 456}
 return 0;
}

代码中的问题是您试图访问位置 i+j 处的字符串内容,但不确定该位置是否超出范围。我对您的代码进行了最少的修改以获得正确的输出(我认为)。