C++ 使用同一函数时如何修改间距

C++ How to modify spacing when using the same function

本文关键字:修改 何修改 函数 C++      更新时间:2023-10-16

假设我有两个函数,每个函数都使用如下所示printInfo()函数:

void printInfo() {
cout << "4spaceshere " << "name";
}
void printMemberInfo() {
printInfo();
}
void printMember() {
printInfo();
}
int main() {
printMemberInfo();
printMember();
return 0;
}

无论如何,我可以在每个函数"name"之前修改空格吗?

例如:printMemberInfo()必须产生这样的输出:3spaceshere nameprintInfo()将打印出5spaceshere name.我尝试了cout << setw()cout.width()但似乎不起作用。希望你们能帮到忙!谢谢!

使用参数让printInfo知道要打印的空格数:

#include <iostream>
#include <iomanip>
void printInfo(int spaces)
{
std::cout << std::setw(spaces) << ' ' << "namen";
}
void printMemberInfo()
{
printInfo(5);
}
void printMember()
{
printInfo(3);
}
int main()
{
printMemberInfo();
printMember();
}

或者让调用函数打印所需的空格:

#include <iostream>
#include <iomanip>
void printInfo(int spaces)
{
std::cout << "namen";
}
void printMemberInfo()
{
std::cout << std::setw(5) << ' ';
printInfo();
}
void printMember()
{
std::cout << std::setw(3) << ' ';
printInfo();
}
int main()
{
printMemberInfo();
printMember();
}

是的...这是一种方法:

int printInfo(int nSpaces) {
for(int j = 0; j < nSpaces; j++)
cout << ' ';
cout << name;
}

然后调用它:

printInfo(1);  // one space
printInfo(4);  // four spaces

如果你不知道怎么做,你需要学习如何传递参数来函数。