Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format output in a table, C++

How can I output data to the console in a table in C++? There's a question for this in C#, but I need it in C++.

This, except in C++: How To: Best way to draw table in console app (C#)

like image 596
JT White Avatar asked Jul 19 '11 23:07

JT White


People also ask

How do we format output in C?

We use the scanf() function for getting the formatted inputs or standard inputs so that the printf() function can provide the program with numerous options of conversion. We use the printf() function for generating the formatted outputs or standard outputs in accordance with a format specification.

What is %s %d in C?

%s refers to a string %d refers to an integer %c refers to a character. Therefore: %s%d%s%c\n prints the string "The first character in sting ", %d prints i, %s prints " is ", and %c prints str[0].

What is %U and %D in C?

%d is a signed integer, while %u is an unsigned integer. Pointers (when treated as numbers) are usually non-negative. If you actually want to display a pointer, use the %p format specifier.

How do I print %d output?

printf("%%d") , or just fputs("%d", stdout) .


2 Answers

I couldn't find something I liked, so I made one. Find it at https://github.com/haarcuba/text-table

Here's an exmaple of its output:

+------+------+----+
|      |Sex   | Age|
+------+------+----+
|Moses |male  |4556|
+------+------+----+
|Jesus |male  |2016|
+------+------+----+
|Debora|female|3001|
+------+------+----+
|Bob   |male  |  25|
+------+------+----+
like image 188
Yoav Kleinberger Avatar answered Oct 15 '22 01:10

Yoav Kleinberger


Here's a small sample of what iomanip has:

#include <iostream>
#include <iomanip>

int main(int argc, char** argv) {
    std::cout << std::setw(20) << std::right << "Hi there!" << std::endl;
    std::cout << std::setw(20) << std::right << "shorter" << std::endl;
    return 0;
}

There are other things you can do as well, like setting the precision of floating-point numbers, changing the character used as padding when using setw, outputting numbers in something other than base 10, and so forth.

http://cplusplus.com/reference/iostream/manipulators/

like image 33
Dawson Avatar answered Oct 14 '22 23:10

Dawson