So, basically I'm creating a program that at certain points needs to display text one character at a time with intervals between each character. I created a function that I can pass a string into that is supposed to display the string one character at a time slowly. The only problem is when I'm taking each character from the string, I get the error -> "terminate called after throwing an instance of 'std::out_of_range'what(): basic_string::at"
I've been trying to find the problem for quite a while and all the other code seems to be working, but code that puts the character from the string into the array of characters I made, and I have no idea how to fix it. Any help is much appreciated.
Code:
std::string SlowText(std::string s)
{
int L = s.length();
char *Text;
Text = new char[L];
int c = L;
while(c > 0)
{
Text[c] = s.at(c);
--c;
}
c = L;
while(c > 0)
{
std::cout << Text[c];
Sleep(250);
--c;
}
return "";
}
The reason is that L
is the length of the array and you do this:
c = L;
because of 0 indexing you are starting past the end of the string. Try this:
c = L-1;
Of course since this is c++, I am going to tell you the standard thing which is don't use arrays! your code could be this:
std::string SlowText(std::string s)
{
for (auto b = s.rend(), e = s.rbegin(); b != e; b++)
{
std::cout << *b << std::flush;
sleep(250)
}
return ""; //Also why have this?
}