21xrx.com
2025-04-09 07:33:24 Wednesday
文章检索 我的文章 写文章
C++如何输出固定长度的字符串
2023-06-27 06:59:40 深夜i     47     0
C++ 输出 固定长度 字符串 格式化输出

在C++中,输出固定长度的字符串可以通过设置输出宽度来实现。其中,设置输出宽度的函数是setw(),其参数为输出宽度。以下是一个例子:

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
  string str = "hello";
  cout << setw(10) << str << endl;
  return 0;
}

运行以上代码,输出结果为:

hello

可以看到,使用setw()函数设置了输出宽度为10,因此字符串前面有空格以达到总长度为10的效果。

另外,如果需要左对齐或右对齐,则可以使用setiosflags()函数设置对齐方式。例如,右对齐可以通过以下方式实现:

#include <iostream>
#include <iomanip>
using namespace std;
int main() {
  string str = "hello";
  cout << setiosflags(ios::right) << setw(10) << str << endl;
  return 0;
}

运行以上代码,输出结果为:

hello

可以看到,输出结果与之前相同,但是字符串是右对齐的。

综上所述,C++中可以使用setw()函数实现输出固定长度的字符串,而setiosflags()函数可以用于设置对齐方式。这些函数都可以通过头文件 包含使用。

  
  

评论区

请求出错了