#include <iostream>
#include <string>

using namespace std;

int main()
{
	string character;
	cout << "capacity: " <<character.capacity() << endl << "Input a sequence: \n";
	getline(cin,character);

	string reversestring;
	int counter = 0;

	for(int i =  character.length() - 1; i >= 0; i--)
	{   
		reversestring[counter++] = character[i];
	}

	cout << reversestring;

	return 0;
}

messing around with a project above and I've hit an error I didn't expect. The program compiles fine, but whenever the user puts in there input I get the error "Debug Assertion Failed".

What can I do about that?

(I know there probably is problems with counter++ where it's at, but noticed a lot of C++ code put increments within the variable and liked the room it saves so messing around with that. Also I need to learn to use pointers, but that's something I plan on doing after I get it working this way.)

>>I know there probably is problems with counter++

You're correct. "reversestring" doesn't have any memory allocated and so you can't access it's elements with the [] operator.
There are 3 ways around it.
1. Allocate the memory. But this is a very "C" solution and not recommended
2. Use the + operator:

string reversestring = ""; // Give it an initial value
[...]
	for(int i =  character.length() - 1; i >= 0; i--)
	{   
		reversestring += character[i]; // Automaticly change the size of reversestring
	}

3. Forget these loops all together and use STL:

#include <string>
#include <iostream>
#include <algorithm>

int main()
{
    std::string test = "Hello, this is a test";
    std::string reversestring = test;
    std::reverse (reversestring.begin(), reversestring.end());
    std::cout << reversestring ;
}

Or

std::string reversestring(test.rbegin(),test.rend());
    std::cout << reversestring;

for that matter.

commented: Yes indeed +15

Think using a built-in function to do it kinda cheats, but initializing the string did work. However, Definitely going to try and remember that. Thanks!

>>Think using a built-in function to do it kinda cheats

If this was an homework assignment, you probably shouldn't use build-in functions because you teacher is trying to teach you something. In all other cases build-in functions are preferable.

oh I'm not some person that thinks I shouldn't use stuff that's given to you freely to make things easier. Just when the question is "Make a function that reverses a string" using someone else's function doesn't accomplish that : P

I'm a hobbyist programmer so I'm just trying to learn the in's and out's of the language currently.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.