我经常遇到想将二维数组打印到屏幕或文件的情况。我的标准做法是这样的:
for(int q=0; q<x; q++)
{
cout << "\n";
for(int w=0; w<y; w++)
cout << number[q][w] << "\t";
}
但是,当元素number
长度不同时,这通常会导致列未正确对齐。如何在每个数字之后(或之前)添加正确数量的空格以使列对齐?
我经常遇到想将二维数组打印到屏幕或文件的情况。我的标准做法是这样的:
for(int q=0; q<x; q++)
{
cout << "\n";
for(int w=0; w<y; w++)
cout << number[q][w] << "\t";
}
但是,当元素number
长度不同时,这通常会导致列未正确对齐。如何在每个数字之后(或之前)添加正确数量的空格以使列对齐?
使用和。std::setw()
_std::left
std::right
#include <iostream>
#include <iomanip>
void printNumber(int x) {
std::cout << "X:" << std::setw(6) << x << ":X\n";
}
void printStuff() {
printNumber(528);
printNumber(3);
printNumber(73826);
printNumber(37);
}
int main() {
std::cout << "Left-aligned\n";
std::cout << std::left;
printStuff();
std::cout << "Right-aligned\n";
std::cout << std::right;
printStuff();
}
输出:
Left-aligned
X:528 :X
X:3 :X
X:73826 :X
X:37 :X
Right-aligned
X: 528:X
X: 3:X
X: 73826:X
X: 37:X
(演示:http: //ideone.com/6IdIc。)
In this example, I've used 6 as the maximum width expected. If you don't know the maximum, you'll either need to do an initial pass through your data to find out, or just use the maximum possible for the data-type you're using (to make this portable, you could use std::numeric_limits<T>::max
).