Reversing a word

so the program i am trying to create takes whatever word you enter and reverses it using the function reverse.

Example: dog --> god, tooth --> htoot...

here's what I have, it keeps telling me std::out of range. what(): basic_string.at. which i don't really understand

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
  // this program reverses the order of letters in a word

#include <iostream>
#include <string>
#include <stdio.h>
using namespace std;

int Reverse(string a);

int main()
{
	string word;
	
	cout << "Enter a word you would like to reverse: ";
	getline(cin, word);
	
	word = Reverse(word);
	
	cout << "\n\nThe new word is: " << word << endl;
}

int Reverse(string a)
{
	int i, newword;
	i = a.length();
	
	for (int b=i; b>0; b--)
	{
		newword += a.at(i);
	}
	
	return newword;
}
Last edited on
.at() indexing is like subscript (array[0]) and as such will be 1-off from counting index (first letter in string is .at(0), etc) and the last "valid" index will be string.at(string.length() - 1); Your i = string.length() so it is 1 over the last character in the string (and thus out of range).
Topic archived. No new replies allowed.