21xrx.com
2025-04-13 01:47:07 Sunday
文章检索 我的文章 写文章
C++语言的左对齐技巧
2023-06-24 01:08:03 深夜i     41     0
C++ 左对齐 技巧 格式化输出 setw()函数

在编程中,有时需要将字符串或数字左对齐,使其保持对齐状态。C++语言提供了一些技巧来实现左对齐,下面我们来介绍一些常用的方法。

一、setw()函数

C++中提供了一个函数setw(),该函数可以用来设置输出的最小字段宽度。当输出的数据不足最小字段宽度时,setw()函数会用空格将其填充至指定宽度。如下所示:

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
  int num = 123;
  cout << setw(6) << num << endl;
  cout << setw(10) << num << endl;
  return 0;
}

输出:

123
    123

二、left、right以及internal控制符

C++中还提供了控制符left、right和internal,它们可以用来设置输出的对齐方式。其中,left表示左对齐,right表示右对齐,internal表示在字段宽度内左对齐(如果有的话),如果输出内容不足,则使用空格填充。如下所示:

#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
  int num = 123;
  cout << left << setw(6) << num << endl;
  cout << right << setw(10) << num << endl;
  cout << internal << setw(8) << num << endl;
  return 0;
}

输出:

123 
    123
  123

三、自定义函数实现左对齐

如果自带的对齐函数无法满足特定的需求,可以自定义函数来实现左对齐。如下所示:

#include <iostream>
#include <string>
using namespace std;
void left_align(string s, int width, char fillchar)
{
  int len = s.length();
  if (len >= width)
  
    cout << s << endl;
  
  else
  {
    int filllen = width - len;
    cout << s;
    for (int i = 0; i < filllen; i++)
    
      cout << fillchar;
    
    cout << endl;
  }
}
int main()
{
  string s = "hello";
  left_align(s, 10, '*');
  left_align(s, 3, '*');
  return 0;
}

输出:

hello*****
hello

总结:

左对齐是编程中非常常见的需求,C++提供了多种方式来实现左对齐,其中包括setw()函数、left、right和internal控制符以及自定义函数。具体使用时,需要根据实际情况选择合适的方法来解决问题。

  
  

评论区