首页 > 解决方案 > 为什么 setw 不显示空格?

问题描述

我有这个代码。它适用于第一个空间,但不适用于第二个空间。谁能告诉我为什么,或者如何解决?

#include <iostream>
#include <iomanip>
#include <vector>
#include <string>
#include <fstream>

using namespace std;

//Constants
const int LENGTH_SPACE = 10;
const int LENGTH_SPACES = 2;

//Structs
struct post_t
{
    int authorID;
    int targetID;
    string message;
};

void displayStruct(post_t &demo)
{
    cout << demo.authorID << setw(LENGTH_SPACE) << demo.targetID << setw(LENGTH_SPACES) << demo.message << endl;
};

int main() {
    post_t demo = {101, 9999, "Just a test"};
    displayStruct(demo);

    return 0;
}

预期输出

101     9999  Just a test

标签: c++

解决方案


您似乎希望setw(LENGTH_SPACE)在其他输出之间简单地添加空格。

为此,您不需要setw(见下文)。它做了什么(cppreference):

当在表达式 out << setw(n) 或 in >> setw(n) 中使用时,将流输出或输入的宽度参数设置为正好 n。

例如这个:

#include <iostream>
#include <iomanip>
int main() {
    std::cout << std::setw(5) << "123" << "\n";
    std::cout << "^^ two spaces added to a 3 characters long output\n";
}

产生输出:

  123
^^ two spaces added to a 3 characters long output

并输出:

#include <iostream>
#include <iomanip>
int main() {
    std::cout << std::setw(2) << "123" << "\n";
    std::cout << "no space added when the length of the string is longer than the requested width\n";
}

123
no space added when the length of the string is longer than the requested width

' '如果您只是想要在结构成员的输出之间有一定数量的空格,那不是什么setw。反而:

std::cout << "a" << std::string(number_of_spaces,' ') << "b";

推荐阅读