Your initial code combines a lot on a single line. I'm breaking it apart for explanation:
int main()
{
cout // cout is "console output" -- i.e. how you print to the screen
<< setfill('0') // This is the operation "cout << setfill('0')"
// which creates a modifier "setfill", passes it to cout,
// and now you've "taught" cout to use '0' as the fill
// character.
// Importantly, "cout << setfill('0')" returns cout...
<< setw(1) // This is the operation "cout << setw(1)".
// It's applying the "<< setw(1)" to the return of the
// previous command. This is also a special modifier,
// and again, this returns 'cout'.
<< hundreds // Now you're finally printing something, because this
// is doing "cout << hundreds"
<< setw(1)
<< tens
<< setw(1)
<< units
<< "\n";
system("PAUSE");
return 0;
}
Importantly, every operation in that long line is cout << {something}
, and the result of the <<
operation is the cout
again -- which is why you can chain the statements together.
Knowing that, you should now be able to see why this fails:
int recomposedEncryptedNumber()
{
return
setfill('0') // This gives you the setfill modifier.
// -- but that's _not_ cout.
<< setw(1) // "setfill << setw"?? Not what you want at all.
// You want "cout << setfill" and "cout << setw".
<< hundreds << setw(1) << tens << setw(1) << units;
}
You have many options on how to proceed. You could do something like this:
int main() {
cout << "The encrypted number is: ";
printRecomposedEncryptedNumber();
cout << "\n";
}
These are three separate statements. Now printRecomposedEncryptedNumber
can print your details to cout directly, and return void (i.e. not return anything).
If you want to do it inline:
int main() {
cout << "The encrypted number is: " << recomposedEncryptedNumber() << "\n";
}
Then your recomposedEncryptedNumber
must return something that can be given to cout
. Since you're trying to do some special formatting, you don't want to use int -- cout will just display the int the way it wants to. So you should use a string. Then your function can do whatever formatting it wants, and return the properly formatted string:
string recomposedEncryptedNumber(int hundreds, int tens, int units)
{
std::ostringstream msg; // 'o' is for output
// 'string' is because we're building a string
// 'stream' is because this uses streaming methods
// i.e. 'ostringstream' lets us build a string,
// by using streaming mechanisms.
// Same stream machinations you were doing before, just with 'msg'
// instead of 'cout'
msg << setfill('0') << setw(1) << hundreds << setw(1) << tens << setw(1) << units;
return msg.str(); // return the string we've built.
}
Lastly, in order for your function to access hundreds
, tens
, units
, the function must be given those variables (i.e. the variables must be passed into the function as parameters).
Welcome to C++!