C++ setw()函数
C++中的setw()函数是定义在头文件
使用方法
setw()函数的使用方法是:
#include#include using namespace std; int main() { cout << setw(10) << "Hello" << endl; return 0; }
其中,setw()函数接受一个参数,表示要设置的宽度,在上面的例子中,它的参数值为10,表示输出的“Hello”占据10个字符宽度,若参数值为20,则输出的“Hello”占据20个字符宽度。
应用示例
setw()函数的应用示例如下:
#include#include using namespace std; int main() { cout << setw(10) << "Name" << setw(20) << "Age" << endl; cout << setw(10) << "Tom" << setw(20) << "18" << endl; cout << setw(10) << "John" << setw(20) << "20" << endl; return 0; }
输出结果如下:
Name Age Tom 18 John 20
从上面的例子可以看出,setw()函数可以用来控制输出的每一个值占据的字符宽度,从而使输出的内容更加美观,更容易阅读。