-1

I am getting Assertion Failed. It show it after cin. I have checked also the file whose path it shows, but no solution. "string iterator + offset out of range" is the massage it shows. It happens after I use "cin >> a" at line 65. Can anyone help me? Thanks in advance.

#include <iostream>
#include <string>
#include <sstream>
#include <vector>
using namespace std;

int gcd(int a, int b){
cout << "gcd" << endl;
if (b == 0) return a;
else return gcd(b, a % b);
}

int gcd_n(vector<int>nums){
int g;

size_t n = nums.size();
    
g = nums.at(0);
cout << "son" << endl;
for (int i = 1; i < n; i++){
        
    g = gcd(nums.at(i), g);
}
return g;
}

long long int multi_vect(vector<int> v){
long long int m = 1;

for (size_t i = 0; i < v.size(); i++)   
    m *= v.at(i);
return m;
}

int main() {
int a;
vector <vector<int>> all_vects;
cin >> a;
string input, sub;

getline(cin, input);
int n = input.find(' ');
vector<int> vect;
while(true){

    int num;
    sub = input.substr(0, n);
    istringstream(sub) >> num;
    vect.push_back(num);

    input = input.substr(n+1, input.back()+1);  
    n = input.find(' ');
    if (n == -1){
        istringstream(input) >> num;
        vect.push_back(num);
        break;
    }
}
all_vects.push_back(vect);
}

1 Answers1

0

When I tested this code, I found that n=-1 needs to be judged in advance. Suppose that input. Assuming that the string input has no ' ', then n will become -1, And the sub = input.substr(0, n); is not true. So, the vector vect will be empty. That is why string iterator + offset out of range will appear.

The following are my changes to this code. And you could refer to it.

    if (n == -1) 
    {
        istringstream(input) >> num;
        vect.push_back(num);
        break;
    }
    else {
        sub = input.substr(0, n);
        istringstream(sub) >> num;
        vect.push_back(num);

        input = input.substr(n + 1, input.back() + 1);
        n = input.find(' ');
    }
Barrnet Chou
  • 1,434
  • 1
  • 2
  • 7