having a funtion store a string that it makes lowercase and returns it for later use in C++

107 views Asked by At

Ok, i have a program I'm trying to make and the basic thing is to keep me from rewriting the same long 4 lines of code over and over throughout the project, I'm wanting to see if i can get it to take a string from cin and make the whole string lowercase (I'm aware of the transform method, but this is so i don't have to write really length if statements) and return that string to be used as a variable in other parts of the program or other functions.

I don't know if I'd just have to make the function's return the variable itself in the main block or what. I'm pretty new to c++ and coding in general, if its possible id like to include spaces, in the string. Again I'm not too experienced in c++ yet so id like to know if its even possible and if so the best way to do it.

here is what i have so far

int loAns() {
    string lAnswer; //Makes the lAnswer, a string used for a long answer that a char wouldn't do properly
    cin >> lAnswer; //User enters it
    // using transform() function and ::tolower
    transform(lAnswer.begin(), lAnswer.end(), lAnswer.begin(), ::tolower); //The transform and ::tolower to make it uniform
    cout << lAnswer << endl; //Outputs the lAnswer to console

    return 0; //This is where I'm assuming the variable gets put to be used in the rest of the program
}
1

There are 1 answers

3
AudioBubble On

Your interpretation is correct. Essentially, a function is declared as such:

type name ( parameter1, parameter2, ...) 
{
    //statements
    return <var>;
}

The type is for returning variables back to other programs. In this case, you want to return a std::string, so you function could be like this:

#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

string loAns()
{
    string lAnswer;
    cin >> lAnswer;
    transform(lAnswer.begin(), lAnswer.end(), lAnswer.begin(), ::tolower);
    return lAnswer;
}

int main()
{
    string s = loAns();
    cout << s;
}

Result :

xYZabC123
xyzabc123

If you wanted spaces in your string, it's possible to use getline():

#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

string loAns()
{
    string lAnswer;
    getline(cin, lAnswer);
    transform(lAnswer.begin(), lAnswer.end(), lAnswer.begin(), ::tolower);
    return lAnswer;
}

int main()
{
    string s = loAns();
    cout << s;
}

Result :

ABc   XYZ   123&A
abc   xyz   123&a
  • More info:

Functions : https://en.cppreference.com/w/cpp/language/functions

return : https://en.cppreference.com/w/cpp/language/return

getline() : https://en.cppreference.com/w/cpp/string/basic_string/getline