C++ 使用同一函数时如何修改间距
C++ How to modify spacing when using the same function
假设我有两个函数,每个函数都使用如下所示printInfo()
函数:
void printInfo() {
cout << "4spaceshere " << "name";
}
void printMemberInfo() {
printInfo();
}
void printMember() {
printInfo();
}
int main() {
printMemberInfo();
printMember();
return 0;
}
无论如何,我可以在每个函数"name"
之前修改空格吗?
例如:printMemberInfo()
必须产生这样的输出:3spaceshere name
,printInfo()
将打印出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
如果你不知道怎么做,你需要学习如何传递参数来函数。
相关文章:
- 使用C++库在Android项目中修改gradle中的cmake参数,用于插入指令的测试
- 独立读取-修改-写入顺序
- 当系统的卷被修改时,如何修改WASAPI环回捕获卷
- 修改函数中的指针(将另一个指针作为参数传递)
- 为什么我可以通过引用修改常量返回
- 对于结构,表达式必须是可修改的ivalue
- QML:修改在不同QML文件(而非main.QML)中定义的子对象的属性
- 为什么不能修改对象中的值?另外,我如何改进此链表?
- 修改创建帐户程序
- 我应该如何修改此代码以使用给定字符串中的字母打印菱形图案
- 如何从子成员函数修改父公共成员变量
- 修改 VS Code 中的默认C++代码段
- 为什么在我的函数类型后使用引用运算符 (&) 允许我修改它返回的值?
- 如何使用递归打印修改后的星号三角形图案
- 已修改的LinkedList未在文本文件本身中更新
- C++RapidXml-使用first_node()遍历以修改XML文件中节点的值
- 为什么可以修改数组 b?
- 将 C++ 类与 Rcpp 一起使用,从 C 或 R 修改它
- 修改的Fibbonaci C++得到一个大的负数
- 将文件的上次修改日期修改为字符串 c++