0

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 "";
}

1 Answers1

2

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?
}
Fantastic Mr Fox
  • 32,495
  • 27
  • 95
  • 175
  • Thank you very much, but as I newcomer to C++, what's wrong with arrays? – user1817251 May 05 '14 at 04:21
  • @user1817251 They are hard, they open you up to memory errors. The best reason is why use them when you have stl types which are better, easier to use, have more functionality and work with std algorithms like sort etc. There is nothing wrong with them but there is no point using them when there is something so much better! – Fantastic Mr Fox May 05 '14 at 21:55