测试案例之间的不同打印格式

时间:2019-03-02 17:09:31

标签: c++ printing format

因此,我在下面有两个测试用例,一个显示正确,另一个不正确。我需要将不正确的一个与正确的一个匹配。如下实现的打印功能。我相信逻辑有些错误。但是我不知道从现在开始该怎么做。我需要您的协助。谢谢。

正确打印:

********** TestSubscript1 **********
Construct from unsigned char array:
2  4  6  6  8  10  6  12  234  14  16  6  6  (size=13, capacity=16)
using subscript: a[6]
a[6] = 6

打印不正确:

********** TestSubscript1 **********
Construct from unsigned char array:
2  4  6  6  8  10 6  12 23414 16 6  6  (size=13, capacity=16)
using subscript: a[6]
a[6] = 6

打印功能:

void Print(const vector<unsigned char>& s)
{
    for(int i = 0; i < s.count; i++) 
    {
        std::cout<<std::setw(3)<<std::left<<(unsigned)s.v[i]; 
    }
std::cout<<std::setw(2)<< "(size=" << s.count << ", " << "capacity=" << 
s.capacity << ")";
std::cout<<std::endl; 
}

2 个答案:

答案 0 :(得分:1)

不设置数字的宽度,只需在数字后放置两个空格:

std::cout << static_cast<unsigned int>(s.v[i]) << "  ";

然后:

std::cout<< "(size=" << s.count << ", " << "capacity=" << s.capacity << ")";

答案 1 :(得分:0)

“正确”的输出并不局限于对所有数字仅使用std::setw(3),就像您在输出中所做的那样。可以使用std::setw(3)代表1位数字,std::setw(4)代表2位数字,而std::setw(5)代表3位数字,然后省略{{1} }:

std::setw(2)

完成相同输出的一种更简单的方法是完全不使用int getw(unsigned char ch) { if (ch < 10) return 1; if (ch < 100) return 2; return 3; ) void Print(const vector<unsigned char>& s) { for(int i = 0; i < s.count; ++i) { unsigned char ch = s.v[i]; std::cout << std::setw(2+getw(ch)) << std::left << (unsigned)ch; } std::cout << "(size=" << s.count << ", " << "capacity=" << s.capacity << ")"; std::cout << std::endl; } std::setw。只需按原样写数字,然后在每个数字后写两个空格:

std::left