您的初始代码在一行中组合了很多内容。我把它拆开来解释:
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;
}
重要的是,该长行中的每个操作都是cout << {something}
,并且<<
操作的结果是cout
再次 - 这就是您可以将语句链接在一起的原因。
知道了这一点,您现在应该能够看到失败的原因:
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;
}
关于如何继续,您有很多选择。你可以这样做:
int main() {
cout << "The encrypted number is: ";
printRecomposedEncryptedNumber();
cout << "\n";
}
这是三个独立的陈述。现在printRecomposedEncryptedNumber
可以直接将您的详细信息打印到 cout,并返回 void(即不返回任何内容)。
如果你想内联:
int main() {
cout << "The encrypted number is: " << recomposedEncryptedNumber() << "\n";
}
然后你recomposedEncryptedNumber
必须返回一些可以给予的东西cout
。由于您正在尝试进行一些特殊的格式化,因此您不想使用 int —— cout 只会以它想要的方式显示 int 。所以你应该使用一个字符串。然后你的函数可以做任何它想要的格式化,并返回正确格式化的字符串:
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.
}
最后,为了让您的函数访问hundreds
, tens
, units
,函数必须被赋予这些变量(即变量必须作为参数传递给函数)。
欢迎使用 C++!