I have tried multiple times to rewrite a given code in do while loop into a while loop and nothing seems to be working. When a rearrange most of the code I receive a debug assertion error upon execution. The purpose of the code is to read in a string and then output the string spelt backwards.
This is the code I have been given;
int main()
{
string word;
cout << "please enter a word: ";
cin >> word;
int length = word.length();
int i = -1;
do
{
i++;
char ch = word[i];
word[i] = word[length-1];
word[length-1] = ch;
} while (i < --length);
cout << word;
return 0;
}
This is the code I have now but when I put in a word the all the letters are coming out reversed but the last one stays in the same place.
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main()
{
string word;
cout << "please enter a word: ";
cin >> word;
int length = word.length();
int i = -1;
for (int i = -1; i < --length; i++)
{
char ch = word[i];
word[i] = word[length-1];
word[length-1] = ch;
}
cout << word;
return 0;
}

New Topic/Question
Reply



MultiQuote




|