-1

I wanted to make a program that assign a string to another string on reverse without using any builtin functions but i got this error,how can i solve it. image

#include <iostream>

using namespace std;
int main()
{
    string a, b;
    
    cin >> a;
    for (int i = 0; i < a.size(); i++)
    {
        b[i] = a[a.size() - 1 - i];
    }
    cout << b;

}
  • as `b` is an empty string only `b[0]` is not out of bounds – 463035818_is_not_an_ai Dec 19 '20 at 15:22
  • When you get that error press Retry and break into the debugger. Then switch the "Stack Frame" on the debug toolbar to your code to see the exact line of your code that was running when the code crashed. – drescherjm Dec 19 '20 at 15:41
  • [Why is “using namespace std;” considered bad practice?](https://stackoverflow.com/questions/1452721/why-is-using-namespace-std-considered-bad-practice) – Gary Strivin' Dec 19 '20 at 17:18

3 Answers3

1

The code does not allocate space for the string b, your code assumes that b has a.size() as size. Which is not true insert the statement b.resize(a.size()) before the loop

Full code:

#include <iostream>

using namespace std;
int main()
{
    string a, b;
    
    cin >> a;
    b.resize(a.size());
    for (int i = 0; i < a.size(); i++)
    {
        b[i] = a[a.size() - 1 - i];
    }
    cout << b;

}
Remy Lebeau
  • 555,201
  • 31
  • 458
  • 770
WARhead
  • 643
  • 5
  • 17
1

Change this

b[i] = a[a.size() - 1 - i];

to this

b += a[a.size() - 1 - i];

Strings (and vectors) do not automatically adjust their size when you use []. If your string has size zero you need to use push_back, resize, += or similar to add characters to it.

john
  • 85,011
  • 4
  • 57
  • 81
0

Replace your code with the following:

#include <iostream>

using namespace std;
int main()
{
  string a="", b="";

cin >> a;
for (int i = 0; i < a.size(); i++)
{
    b+= a[a.size() - 1 - i];
}
cout << b;

return 0;
}
nissim abehcera
  • 821
  • 6
  • 7