reverse a string... help

Write your question here.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
#include <iostream>
#include <string>
using namespace std;


int main() {
string input;
    string output;
    string temp;
    cout << "Enter your input"<< endl<<input;
    getline(cin, input);
    for(int i; i< input.length(); i++){
   output = input[i] + output;
   cout<<output<<endl;
   }
return 0;
}


/*I'm printing 
c
lc
alc
ualc
dualc
idualc
aidualc


I want to be able to print the last thing of my for loop :  aidualc

I do not want to use the reverse function included in the library
*/

Last edited on
Your program is fine.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
#include <iostream>
#include <string>
using namespace std;


int main() {
string input;
    string output;
    string temp;
    cout << "Enter your input"<< endl << input;
    getline(cin, input);
    for(int i = 0; i < input.length(); i++){
   output = input[i] + output;
   cout<<output<<endl;
   }
return 0;
}


/*I'm printing 
c
lc
alc
ualc
dualc
idualc
aidualc


I want to be able to print the last thing of my for loop :  aidualc */


Remember to initialize variables before using them.
This is what your program is doing

1. Get string from user. In this case, it is "claudia"
2. You use the for-loop

From i to input.length()
- You concatenate each character of input[i] and output string variable.
- You print output string variable with each iteration of the for loop.

Some things I'd like to point out
1. string temp variable is declared but it is never used. Why is it even there?
2. You need to initialize your variables even if they are empty or 0. You are depending on the OS to fill empty memory with 0.
For example
1
2
3
string output = "";

for( int i = 0 ; i < input.length() ; i++ )



Lastly, if you want to print the last thing of your for loop, simply take Line 14 out of the for loop.


Last edited on
Hello claudilla,

Lastly, if you want to print the last thing of your for loop, simply take Line 14 out of the for loop.

Or just move line 14 outside of the for loop.

Andy
Thank you guys!
Topic archived. No new replies allowed.