Aug 2, 2016 at 3:55pm UTC
A little help with my program please. I'm trying to print out an inputted string in reverse
----> John Cena = aneC nhoJ
1 2 3 4 5 6 7 8 9 10 11
void printReverse (string str)
{
string reverseLetter [str.length()];//This string is suppose to contain the characters of str sorted in reverse.
int r = 0;
for (int n=str.length();n>=0; n--) //Loop through each of the characters of str, from the last to the first.
{
str [n] = reverseLetter[r]; //Tried to assign the last value of str to the first of reverseLetter.
r++;
}
}
Last edited on Aug 2, 2016 at 3:55pm UTC
Aug 2, 2016 at 4:02pm UTC
Hi,
Try this :
1 2 3 4 5 6
void printReverse (string str)
{
string reserveStr;
for (int i = str.length() - 1; i >= 0; i--) reserveStr += str[i];
cout << reserveStr;
}
Last edited on Aug 2, 2016 at 4:04pm UTC
Aug 2, 2016 at 4:05pm UTC
I edited my solution.
Now everything works fine.
Aug 2, 2016 at 4:13pm UTC
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21
#include <iostream>
#include <string>
#include <cstdint>
int main ()
{
std::string myString = "This is a sample string I will reverse" ;
std::cout << "Printing the string forwards:\n" ;
for (uint16_t loop = 0; loop < myString.size(); loop++)
{
std::cout << myString[loop];
}
std::cout << "\n\nPrinting the string backwards:\n" ;
for (size_t loop = myString.size(); loop > 0 ; loop--)
{
std::cout << myString[loop - 1];
}
std::cout << "\n" ;
}
Printing the string forwards:
This is a sample string I will reverse
Printing the string backwards:
esrever lliw I gnirts elpmas a si sihT
Last edited on Aug 2, 2016 at 4:13pm UTC
Aug 2, 2016 at 4:22pm UTC
FurryGuy:
I wrote my code that way but what i was trying to do is to assign the reversed string to a new variable. Thank you anyways.
closed account 5a8Ym39o6:
Thank you, this works perfectly, would you be so kind to briefly explain how is it that it works?
Why do you use "str.length() -1"
And how does this work -> reserveStr += str[i];
I thought you had to use a string array so you were able to assign each character to an element.
Last edited on Aug 2, 2016 at 4:29pm UTC
Aug 2, 2016 at 4:29pm UTC
> Thank you, this works perfectly, would you be so kind to briefly explain how is it that it works?
string reserveStr;
This line creates an empty string.
for (int i = str.length() - 1; i >= 0; i--) reserveStr += str[i];
Appends a new character (str[i]) at the end of the reserveStr string every per loop.
Aug 2, 2016 at 4:41pm UTC
> Why do you use "str.length() - 1"
An array subscript starts at 0, and finishes at size - 1
And str.length() - 1 is equivalent to str.size() - 1
Aug 2, 2016 at 4:57pm UTC
Thank you very much, you are a genius
Aug 2, 2016 at 5:47pm UTC
@Thomas1965, I was going to mention reversed iterators.
your code is much neater than what I had, using the constructor. Ooops!