I don't understand how to return a string from a function

closed account (EAp4z8AR)
I needed to create a program that would make the first letter of every word uppercase and I think I got that part but I still don't understand how I would return a string from the function. Any help is appreciated thank you.

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
int main()
{
    string statement;
    cout << "Please enter a string to test: \n";
    getline(cin, statement);
    
    string titleCase(string statement);
    return 0;
    
}

string titleCase(string input)
{
    input[0] = toupper(input[0]);
    
    for (int i=1; i<=input.length(); i++)
    {
        if (input[i-1] == ' ')
        {
            input[i] = toupper(input[i]);
        }
        else
        {
            input[i] = tolower(input[i]);
        }
    }
    
    return input;
}
Your function is returning the string just fine.

The problem is that your main function isn't calling titleCase properly.

Look at line 7. That isn't how you call a function.
closed account (EAp4z8AR)
Ahh thank you, I forgot to delete the string in front of it.
closed account (EAp4z8AR)
Even with that fixed the function is not returning the string, it keeps end with a segmentation fault and the debugger says that it can not convert type int to type string in the return statement
closed account (EAp4z8AR)
Got it for anyone who would want to see the finished result.

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
int main()
{
    string statement;
    cout << "Please enter a string to test: \n";
    getline(cin, statement);
    
    statement = titleCase(statement);
    cout << statement << "\n";
}

string titleCase(string input)
{
    input[0] = toupper(input[0]);
    
    for (int i=1; i<=input.length(); i++)
    {
        if (input[i-1] == ' ')
        {
            input[i] = toupper(input[i]);
        }
        else
        {
            input[i] = tolower(input[i]);
        }
    }
    
    return input;
}
i take the code from vmansuria i hope he alllows me to copy
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
#include <iostream>
#include <string>
using namespace std;

string titleCase(string input); // i hope you added this

int main()
{
    string statement;
    cout << "Please enter a string to test: \n";
    getline(cin, statement);
    
    statement = titleCase(statement);
    cout << statement << "\n";
}

string titleCase(string input)
{
    input[0] = toupper(input[0]);
    
    for (int i=1; i<=input.length(); i++)
    {
        if (input[i-1] == ' ')
        {
            input[i] = toupper(input[i]);
        }
        else
        {
            input[i] = tolower(input[i]);
        }
    }
    
    return input;
}
Last edited on
Topic archived. No new replies allowed.