I don't understand how to return a string from a function
Nov 9, 2018 at 5:52pm UTC
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;
}
Nov 9, 2018 at 6:17pm UTC
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.
Nov 10, 2018 at 8:27pm UTC
Ahh thank you, I forgot to delete the string in front of it.
Nov 10, 2018 at 8:32pm UTC
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
Nov 10, 2018 at 8:50pm UTC
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;
}
Nov 11, 2018 at 6:17pm UTC
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 Nov 15, 2018 at 5:47pm UTC
Topic archived. No new replies allowed.