-2
string binary = "12345";
string binary2 = "";
size = binary.size() - 1;
for (i = size; i >= 0; i--)
{
    binary2[size - i] = binary[i];
}
cout << binary2;

I keep getting a subscript error during run time. But, I don't know what the problem is. I would appreciate an explanation if possible.

user29568
  • 167
  • 9

3 Answers3

8

binary2 is empty. It has no characters in it. Accessing characters with [] does not magically create character that do not already exist: it only changes the value of existing characters. You are trying to change the value of characters that do not exist.

You can either initialise binary2 to " ", like this:

string binary = "12345";
string binary2(binary.size(), ' ');
// now your loop

or you can do string reversing properly:

string binary = "12345";
string binary2(binary.rbegin(), binary.rend());
Lightness Races in Orbit
  • 378,754
  • 76
  • 643
  • 1,055
  • A more rigid option for #1 in case `binary` changes would be `string binary2(binary1.size(), '\0');` (or another character of your choosing). – chris Feb 26 '14 at 13:05
  • I haven't learned that yet. Thanks for the addition. Out of curiosity, is their a way to initialize a string to a certain size that is given in a number and can change. Because if I used spaces and binary changed to 123456. It wouldn't work, – user29568 Feb 26 '14 at 13:06
  • @user29568: Why are you not using any documentation? There is a string constructor to do this. http://en.cppreference.com/w/cpp/string/basic_string/basic_string – Lightness Races in Orbit Feb 26 '14 at 13:08
  • @LightnessRacesinOrbit To be honest, our teacher just throws things on the board and doesn't really explain things. So, I haven't learned that either. I use Programming and Principles using C++ by Stoustrup to study. But, I haven't reached that far in yet. – user29568 Feb 26 '14 at 13:11
  • Thank You for offering a full explanation and answer. – user29568 Feb 26 '14 at 13:15
2

First of all your binary2 string is empty. This could be fixed by appending to it instead. However a little bit of searching led me to the following answer by Greg Rogers found here: https://stackoverflow.com/a/198210/2299061

#include <algorithm>
std::reverse(str.begin(), str.end());
Community
  • 1
  • 1
This
  • 45
  • 1
  • 5
  • That is for reversing a string in place, but OP wants a second string to be a reversed version of a first one. In this case, the reverse operator initialization seems more efficient. But +1, `std::reverse` is often overlooked. – juanchopanza Feb 26 '14 at 13:15
0

string binary2 = "" should be changed to string binary2 = " ";

juanchopanza
  • 223,364
  • 34
  • 402
  • 480
gtv
  • 21
  • 1
  • 3