program crashes reversing a string

not too sure why my program crashes

here is the block of code causing the crash

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
  string first;

	cin >> first;
    cout << first.size();
	string reverse;
	int j = 0;

	for(int i = first.size()-1; i > 0; i--){

        reverse.at(j) = first.at(i);

        j++;


	}

	cout << reverse << endl;


here is the exception I get

hey

This application has requested the Runtime to terminate it in an unusual way.
Please contact the application's support team for more information.
3terminate called after throwing an instance of 'std::out_of_range'
what(): basic_string::at: __n (which is 0) >= this->size() (which is 0)
Last edited on
What is the size of the string reverse. And what would be the range of valid subscripts to access its contents?
I didn't initialise reverse so I am guessing the size of = 0?
Well, yes. Though if you're not sure you could check with the size() function. Also that is exactly the information that the error message is giving you:
this->size() (which is 0)


There are lots of ways to do this. To continue with your present plan of attack, you might do this:
1
2
3
4
    string first;
    cin >> first;
    cout << first.size();
    string reverse(first.size(), ' ');

The constructor sets reverse to the same size as first, and fills it with spaces.
great idea Chervil =)

I decided to just implement it with an old c style string instead

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17

char *start = &word[0];
    char *end = &word[size-2];
    char *current = end;

    while(current != start){

    	cout << *current;
    	current--;

    	if(current == start){

    		cout << *current;
    	}
    }

Ok. It's good to know different ways of doing things. For example using std::string,
1
2
    string reverse(first.rbegin(), first.rend());
    cout << reverse << endl;


or from the <algorithm> header, there is std::reverse.
http://www.cplusplus.com/reference/algorithm/reverse/

http://www.cplusplus.com/reference/string/string/rbegin/
http://www.cplusplus.com/reference/string/string/rend/
very true

sometimes there is no need to reinvent the wheel
Topic archived. No new replies allowed.