0

I'm making a simple number reverse program and I've tried many different ways to convert the string to an int but all I get is errors or "core dumped" while executing or compiling. I'm new to C++.

#include <bits/stdc++.h>
using namespace std;

void solve(){
    string n, ans=""; 
    cin >> n; 

    for(int i=0; i<n.length()+1;++i){
        ans += n[n.length()-i];
    }
    int num = stoi(ans);

    cout << ans << "\n";
} 
int main() {
    ios::sync_with_stdio(false);
    cin.tie(NULL);

    int t;
    cin >>t;

    while(t--){
        solve();
    }
    return 0;
} 
Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • How does repeatedly adding the last character of `n` into `ans` solve your problem? What is that supposed to accomplish? – Sam Varshavchik May 15 '21 at 17:23
  • @SamVarshavchik OP is appending the `n.length()-i` element (not the last each time, as `i` changes). But therein lies the problem, on the first loop. – Adrian Mole May 15 '21 at 17:36

1 Answers1

2

Your for loop is accessing an out-of-bounds element of the n string on its first iteration: when i is zero, you are attempting to access the n.length() element of n but the last element is at position n.length() - 1. Remember that arrays, strings and other 'containers' in C++ start at element 0 and end at element n-1 – where n is the size (length) of the container.

You can fix this by starting your loop with i = 1 rather than with i = 0.

#include <iostream>
#include <string>
using std::string;
using std::cout, std::cin; // Pre C++17, you'll need 2 separate "using" statements.

void solve()
{
    string n, ans = "";
    cin >> n;
    for (size_t i = 1; i <= n.length(); ++i) {
        ans += n[n.length() - i];
    }
    int num = stoi(ans);
    cout << num << "\n"; // I've changed to print "num" rather than "ans"
}

int main()
{
//  For someone who is "new to C++," the following two lines are probably overkill...
//  std::ios::sync_with_stdio(false);
//  cin.tie(NULL);
    int t;
    cin >> t;
    while (t--) {
        solve();
    }
    return 0;
}

Also please read Why should I not #include <bits/stdc++.h>? and Why is "using namespace std;" considered bad practice?

On the issue I've commented as "overkill," see: Significance of ios_base::sync_with_stdio(false); cin.tie(NULL); (especially the top/accepted answer).

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83
  • thank you for your answers and the tip – Adrian Otgonzaya May 15 '21 at 18:45
  • @Adrian You're very welcome. You may also like to use the functions provided by the STL. `std::reverse(n.begin(), n.end());` will reverse your string *in place*. [Link](https://en.cppreference.com/w/cpp/algorithm/reverse) – Adrian Mole May 15 '21 at 19:03