简体   繁体   English

如何将 std::setw() 与数组输出一起使用?

[英]How can you use std::setw() with array output?

I am making a blackjack game in C++, and I am trying to print out the players and dealers cards in addition to their sums, capital and so on.我正在用 C++ 制作一个二十一点游戏,我试图打印出玩家和经销商的卡片以及他们的总和、资本等。 However I'm running into an issue with std::setw() when printing out the vector of cards.但是,我在打印卡片向量时遇到了std::setw()问题。 Here is a code snippet:这是一个代码片段:

    int width = 18;
    std::cout << std::left << std::setw(width) << "Your cards:";
    std::cout << std::left << std::setw(width * 2) << "arr";
    std::cout << std::left << std::setw(width) << "Dealers cards:";
    std::cout << "arr2" << std::endl;

    std::cout << std::left << std::setw(width) << "Your sum:";
    std::cout << std::left << std::setw(width*2) << player.sum();
    std::cout << std::left << std::setw(width) << "Dealers sum:";
    std::cout << dealer.sum() << std::endl;

我的代码片段是什么样的

Where arr and arr2 is there should be number values like 5 2 6 1 , but if I print each element separately the with alignment will break. arrarr2在哪里应该有像5 2 6 1这样的数值,但是如果我单独打印每个元素, with 对齐就会中断。 I think for setw() to work it needs to be one block or string, or else the vertical alignment will mess up once the values change.我认为setw()工作,它需要是一个块或字符串,否则一旦值改变,垂直对齐就会混乱。 I tried myString.push_back() for each vector value and then printing that, with no luck.我为每个向量值尝试了myString.push_back() ,然后打印出来,但没有运气。 I assume I need to find a way to print the string into one element.我假设我需要找到一种方法将字符串打印到一个元素中。

This is what it should look like:它应该是这样的:

Your cards:     5 7 1 2                 Dealers cards:     2 1 7 5
Your sum:       21                      Dealers sum:       21
Your capital:   100                     Dealers capital:   100

I have found a solution.我找到了解决办法。 You can use stringstream to add int values to a string with no errors in conversion, this is how I fixed my code:您可以使用 stringstream 将 int 值添加到没有转换错误的字符串中,这就是我修复代码的方式:

#include <sstream>
std::stringstream playerCards{};

for (int i{}; i < player.cards.size(); i++) {
    playerCards << player.cards[i] << " ";
}

int width = 18;
std::cout << std::left << std::setw(width) << "Your cards:";
std::cout << std::left << std::setw(width * 2) << playerCards.str();

This way the array will get put into a string and will count as one block, which is what I was looking for.这样,数组将被放入一个字符串中并算作一个块,这正是我要找的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM