-2

Let's say I have a char variable, and an integer variable. I want to treat them as one variable when I'm outputting them (ex: B6, A2, C10, etc)

I want to right justify both of these variables in a 4 space slot, but I can't for the life of me figure out how to do so. (I want _A10 and __A6 where the underscore is spaces)

Is it possible to do this in C++?

  • The solution I have is to make an if statement and check if the integer variable is >= 10 before outputting both variables and spaces, but this makes the code hard to read. I was wondering if there is an iomanip solution – Geoff Huang Apr 26 '17 at 03:52
  • These type of questions become much easier to answer when you realize what the computer has to do. Since it's printing from left to right, printing `__A6` means that it needs to print two spaces before A, and then a 6. The key word is _before_. You have to know the last variable to print before you start printing space characters. – MSalters Apr 26 '17 at 07:41
  • MSalters, if you look at my comment, I already mentioned that, and discussed my own workaround (which would be even more tedious if the integer variable could be 3 digits, or 4 digits, etc). However, I have gotten an iomanip solution from other comments already, although I'm still not sure what your comment is aiming at. – Geoff Huang Apr 27 '17 at 05:19

2 Answers2

1

Here's a solution without the Boost dependency. Convert the integers to a string, concatenate with the char, and set the stream width with std::setw. For example:

#include <iostream>
#include <iomanip>
int main(void)
{
    char a = 'A', b = 'B';
    int ai = 10, bi = 6;
    std::cout << std::setw(4) << (a + std::to_string(ai)) << std::endl;
    std::cout << std::setw(4) << (b + std::to_string(bi)) << std::endl;
}

On my machine this prints:

 A10
  B6
bnaecker
  • 6,152
  • 1
  • 20
  • 33
0

Use Boost.Format to apply printf-style formats to C++ streams.

#include <iostream>
#include <string>
#include <boost/format.hpp>

int main()
{
  char c = 'A';
  int i = 10;
  std::cout << boost::format("|%4s|") % (c + std::to_string(i)) << '\n';
}

Output:

| A10|
Henri Menke
  • 10,705
  • 1
  • 24
  • 42
  • 1
    Boost is not needed, as long as the column and row name are joined first as you show, the justification can be accomplished using `std::right` and `std::setw`, as shown in http://stackoverflow.com/q/5201619/103167 – Ben Voigt Apr 26 '17 at 04:02
  • Thank you both. And Ben, you're right that I don't need boost for Henri's solution, but I'm glad I was introduced to it just in case I need it in the future. – Geoff Huang Apr 26 '17 at 04:38