Working functions, but a problem carrying over

Hi,
I have two functions outside of main: one takes a string and converts it to lowercase, and one reverses a string.

Now, both functions perform their individual tasks, but when I try to call them both with input in my main, they don't work in tandem.


pseudo code:
lower func(x)
reverse func(y)

main
cin string (TULIP)
lower
reverse
output tulipPILUT



The reverse function only reverses the original input, not the lowercase filter version. I want it to output -pilut instead of PILUT

Here's my code.


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
36
37
38
 #include <iostream>
#include <stdio.h>
#include <ctype.h>
#include <locale.h>
#include <limits.h>
#include <string>
#include <algorithm>
#include <bits/stdc++.h> 
using namespace std;


string Pal (string sent)
{
    for (int i=0; sent[i]; i++) 
    {
        string pal;
        pal = tolower(sent[i]);
        cout << pal ;
    }
    return sent;
}

string Reverse (string rev)
{ 
    string str = rev; 
    reverse(str.begin(), str.end());    
    cout << str; 
    return rev; 
} 


int main ()
{
    string x;
    cin >> x;
    string rev = Pal (x);
    Reverse (rev);
}


** EDIT **
I'm only doing the multiple couts in testing so I can see what each function is doing. I'll clean that up in my final draft. And yes, this is obviously homework.
Last edited on
Hello jjordan33,

The reason your function "Reverse" is not working is because you are returning the wrong string from the function "Pal".

When "Pal" is called it ends up in the variable "sent". You try to put the lower case letters in the variable "pal", but that is lost when the for loop ends.

Between the variables "sent" and "pal" think about which one needs to be returned.

In the end the whole function needs redone and the variable "pal" is not even needed. As it is "pal" is defined inside the function and is lost when the function ends, so you can not even use it. This is a much simpler function:

1
2
3
4
5
6
7
8
9
10
11
string Pal(string sent)
{
	//string pal;
	
	for (int i = 0; sent[i]; i++)
		sent[i] = tolower(sent[i]);
	
	cout << sent << std::endl;

	return sent;
}

Now when you use the return value in "main" to call "Reverse" you will be using all lower case letters.

"Reverse" is working. I will take a closer look at it shortly.

Hope that helps,

Andy
Hey,

Mannnnnnnnnnnnn. I caught myself thinking it had something to do with the return, but I kept getting errors with my attempts at fixing it.

This makes much more sense. Thanks.
Topic archived. No new replies allowed.