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).