substring is out of range error

I am writing up a function that reverses the order of the string "rdd" to "ddr",
when I run it I get an error that substring is out of range. Any help is appreciated!


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
#include <iostream>
#include <string>
#include <stdio.h>
#include <ctype.h>
using namespace std;

string reverse(const string & s);

int main() {
	cout << reverse("rdd") << endl;
}

string reverse(const string & s) {
	string rname(s);
	for (unsigned i = rname.size()-1; i >= 0; i--) {
		cout << rname[i];
	}
	cout << endl;
	return rname;
}
Use 'int'. An unsigned integer will ALWAYS be greater than or equal to 0, so your loop will never exit because the boolean condition is always true.
1
2
3
	for (int i = s.size() - 1; i >= 0; i--) {
		std::cout << s[i];
	}


You could also use iterators.
1
2
3
4
5
string reverse(const string & s) {
	string toRev = s;
	std::reverse_iterator<std::string::iterator> revIter = toRev.rbegin();
	return std::string(revIter, toRev.rend());
}
Last edited on
Imagine calling this function with an empty string:
size() will return 0;
your attempt to assign -1 to an unsigned then results (probably) in i being set to the maximum positive value of int
your rname[i] is now definitely out of range, since the string is empty

A different scenario, what will happen to i when "i == 0" and you run "i-- "? remember i is unsigned

Consider PP's advice about iterators and maybe look up some information on range for, for_each, etc.

Generally, try and use the proper type for holding the size of the string:

std::string::size_type
Topic archived. No new replies allowed.