I need to write a program that takes user\'s input of a string and then print it
ID: 674224 • Letter: I
Question
I need to write a program that takes user's input of a string and then print it in backwards without using any global variables. When I run this code it keeps giving me an Abort() error. Can someone fix it?
#include <iostream>
#include <string>
using namespace std;
void reverse(string w);
int main()
{
string word;
cout << "Enter a word: ";
cin >> word;
cout << "The word in reverse is: " ;
reverse(word);
cout << endl;
return 0;
}
void reverse(string w)
{
if (w.length() == 0)
cout << w;
else
reverse(w.substr(1));
cout << w.at(0);
}
Explanation / Answer
#include <iostream>
#include <string>
using namespace std;
void reverse(string w);
int main()
{
string word;
cout << "Enter a word: ";
cin >> word;
cout << "The word in reverse is: " ;
reverse(word);
cout << endl;
return 0;
}
void reverse(string w)
{
for(int i=w.length()-1;i>=0;i--)
cout << w[i];
}