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
}
Your interpretation is correct. Essentially, a function is declared as such:
The
type
is for returning variables back to other programs. In this case, you want to return astd::string
, so you function could be like this:Result :
If you wanted spaces in your string, it's possible to use
getline()
:Result :
Functions : https://en.cppreference.com/w/cpp/language/functions
return
: https://en.cppreference.com/w/cpp/language/returngetline()
: https://en.cppreference.com/w/cpp/string/basic_string/getlineRan on Code::Blocks 20.03, Windows 10 64-bit
Also, as @David C. Rankin mentioned below,
using namespace std;
is not considered a good practice.