Shawn S.
Shawn S.

Reputation: 97

Cannot Loop Through Two Arrays with Two For Loops

My project is a simple one, I was just going to type text into the console and it was going to write the input text backwards, here is the code:

void Main::getText()
{
    cout << "Insert Text Here: ";
    cin >> text;
    textLength = text.size();
}

void Main::convertText()
{
    for(y = 0;y <= textLength; y++)
    {
        for(x = textLength; x >= 0; x--)
        {
            convertedText[y] = text[x];
        }
    }
}

The problem is that when it gets to convertText() function the console crashes. If anyone can help I would appreciate it.

Upvotes: 0

Views: 56

Answers (1)

Himanshu
Himanshu

Reputation: 4395

First you need to declare all the variables and then
Try this code to save reverse of the string:

int y = 0;
for(int x = textLength-1; x >= 0; x--) //suppose if stringlenght is 6 then index will(0 - 5)
{                                  // so Use textLength-1 to access last index
     convertedText[y++] = text[x];
}
convertedText[y] = '\0';

Upvotes: 2

Related Questions