wasp256
wasp256

Reputation: 6252

Formatted output in C++

I am playing around with the setw and setfill functions but I'm absolutely stuck now. Here is my code:

char separator = ' ';

cout << "-" << setw(INET_ADDRSTRLEN*4 + INET6_ADDRSTRLEN) << setfill('-') << "\n";
cout << "| Name" << setw(INET_ADDRSTRLEN) << setfill(separator);
cout << "| IPv4" << setw(INET_ADDRSTRLEN) << setfill(separator);
cout << "| IPv6" << setw(INET6_ADDRSTRLEN) << setfill(separator);
cout << "| Netmask" << setw(INET_ADDRSTRLEN) << setfill(separator);
cout << "| Broadcast" << setw(INET_ADDRSTRLEN) << setfill(separator);
cout << "|\n";
cout << "-" << setw(INET_ADDRSTRLEN*4 + INET6_ADDRSTRLEN) << setfill('-') << "\n";

while (iter != this->iface.end()) {
    cout << "| " << (*iter).iface_name << setw(INET_ADDRSTRLEN) << setfill(separator);
    cout << "| " << (*iter).ipv4 << setw(INET_ADDRSTRLEN) << setfill(separator);
    cout << "| " << (*iter).ipv6 << setw(INET6_ADDRSTRLEN) << setfill(separator);
    cout << "| " << (*iter).netmask << setw(INET_ADDRSTRLEN) << setfill(separator);
    cout << "| " << (*iter).broadcast << setw(INET_ADDRSTRLEN) << setfill(separator);
    cout << "|\n";
    iter++;
}

And here is my output. How can I fix the alignment of the columns?

--------------------------------------------------------------------------------------------------------------
| Name          | IPv4          | IPv6                                     | Netmask     | Broadcast              |
--------------------------------------------------------------------------------------------------------------
| lo              | 127.0.0.1              | ::1                                            | 255.0.0.0              | 127.0.0.1              |
| eth0              | 192.168.1.100              | fe80::2ad2:44ff:fe39:f798                                            | 255.255.255.0              | 192.168.1.255              |
| wlan0              | 192.168.1.103              | fe80::e8b:fdff:fe7c:bf5                                            | 255.255.255.0              | 192.168.1.255              |

Upvotes: 0

Views: 101

Answers (1)

Barry
Barry

Reputation: 304132

You want to left-align your padded fields, it'll be simpler to reason about (see std::left):

std::cout << std::setw(INET_ADDRSTRLEN) << std::left << iter->iface_name
          << "| " 
          << std::setw(INET_ADDRSTRLEN) << std::left << iter->ipv4
          << "| "
          << std::setw(INET6_ADDRSTRLEN) << std::left << iter->ipv6
          // etc.

As-is, your columns aren't based on your string lengths but rather on the spaces which follow them - which logically aren't constant-width.

Upvotes: 3

Related Questions