moab Gresa
moab Gresa

Reputation: 1

I dont understand this: terminate called after throwing an instance of 'std::length_error'

First of all, I'm not English, so I will try to explain as good as I can. I throw this thread, where saludo means greet, retardo means delay, numero means number, I also create veces for saying the many times that this will happen. So what I have to do, is to create 10 threads, that will show in screen from 5 to 15 times, and with a delay from 100 to 300, that they are a number("Soy" number), but I have that error which I can't solve at all. It works for 2-3 threads and then stop. Thanks btw.

#include <iostream>
#include <thread>
#include <string>
#include <chrono>
#include <time.h>

using namespace std;

void saludo(string m, int retardo, int numero) {
    string tabs(numero - 1, '\t');
    cout << tabs << m << numero << +"\n";
    this_thread::sleep_for(chrono::milliseconds(retardo));
}

int main() {
    int nthread = 10;
    srand(time(NULL));
    thread P[nthread];
    int i = 0;

    while(i<nthread){
        int retardo = rand() % 201 + 100;
        int veces = rand() % 11 + 5;

        for (int x = 0; x<veces; ++x){
            int numero = rand() % 10;
            P[i] = thread(&saludo, "Soy  ", retardo, numero);
            P[i].join();
        }
    }

    cout << "Fin\n"; 
    return 0;
}

Upvotes: 0

Views: 450

Answers (1)

nishantsingh
nishantsingh

Reputation: 4662

This error is because you might have passed negative number to std::string constructor. rand() % 10 might give 0. And you're doing string tabs(numero - 1, '\t'); which is a problem if numero is 0.

Upvotes: 3

Related Questions