I'm a newbie. For a school project, I need a typewriter, and I came down to this idea that seems good to me. But when I launch it, it says this error:
terminate called after throwing an instance of 'std::out_of_range' error
I don't know why. I think the idea is good, because when I try without the variable t
, so just putting numbers in testo.erase()
, it works, but I need to create a loop.
void typewriter(string testo, int tempo)
{
int i = testo.length();
int t = 0;
while (t<=i)
{
system ("CLS");
t=t 1;
testo.erase(t);
cout<<testo;
Sleep(tempo);
}
}
CodePudding user response:
This is because you are erasing the characters, which shortens the string. I think that changing testo.erase(t)
to test.erase(0)
should fix it.
Also, as πάντα ῥεῖ said, it should be t < i
instead of t <= i
. But, this is an unnecessary change, as with the erasing of characters.
CodePudding user response:
Thanks, I resolved it by reassigning the string testo
every time I join in the while
loop:
void typewriter(string testo, int tempo)
{
int i = testo.length();
int t = 0;
string testo1 = testo;
while (t<i)
{
testo1 = testo;
system ("CLS");
t=t 1;
testo1.erase(t);
cout<<testo1;
Sleep(tempo);
}
}