User Input in the Terminal

Formatting Console Output in C++

How can I format console output to create more visually appealing displays?

Abstract art representing computer programming

Formatting console output can greatly enhance the user experience of your C++ applications. There are several techniques you can use to create more visually appealing displays. Let's explore some of theseΒ methods:

1. Using Escape Sequences

Escape sequences allow you to control cursor position and clear theΒ screen:

#include <iostream>

int main(){
  // Clear screen
  std::cout << "\033[2J\033[1;1H";

  // Move cursor to row 5, column 10
  std::cout << "\033[5;10H"
    << "Hello, World!";

  // Move cursor down 2 lines and right 5 spaces
  std::cout << "\033[2B\033[5C"
    << "Welcome to C++!";
}

This example demonstrates clearing the screen, positioning the cursor, and moving it relative to its currentΒ position.

2. Creating Boxes and Lines

You can use ASCII characters to create boxes andΒ lines:

#include <iostream>
#include <iomanip>

void drawBox(int width, int height){
  std::cout << "β”Œ" << std::string(
    width - 2, '─') << "┐\n";
  for (int i = 0; i < height - 2; ++i) {
    std::cout << "β”‚" << std::string(
        width - 2, ' ')
      << "β”‚\n";
  }
  std::cout << "β””" << std::string(
    width - 2, '─') << "β”˜\n";
}

int main(){
  drawBox(20, 5);

  // Position text inside the box
  std::cout << "\033[3;3H"
    << "Hello, World!";

  std::cout << std::endl;
}

This creates a simple box using ASCII characters and positions text insideΒ it.

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                  β”‚
β”‚  Hello, World!   β”‚
β”‚                  β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜

3. Using Color and Text Styling

As we saw in the previous answer, you can use ANSI escape codes for color and textΒ styling:

#include <iostream>

#define RESET "\033[0m"
#define BOLD "\033[1m"
#define RED "\033[31m"
#define GREEN "\033[32m"
#define BLUE "\033[34m"
#define CYAN "\033[36m"

int main(){
  std::cout << BOLD << RED << "Error: " << RESET
    << "Something went wrong!\n";
  std::cout << GREEN << "Success: " << RESET
    << "Operation completed.\n";
  std::cout << BLUE << "Info: " << RESET
    << "This is some information.\n";
  std::cout << CYAN << "Debug: " << RESET
    << "Variable x = 42\n";
}
Error: Something went wrong!
Success: Operation completed.
Info: This is some information.
Debug: Variable x = 42

This example shows how to use different colors and text styles to highlight different types ofΒ messages.

4. Creating Tables

You can use std::setw and std::setfill to create alignedΒ tables:

#include <iostream>
#include <iomanip>

int main(){
  std::cout << std::setfill('-') <<
    std::setw(40)
    << "-" << std::endl;

  std::cout << std::setfill(' ');

  std::cout << "| " << std::left <<
    std::setw(20)
    << "Name" << "| " << std::right <<
    std::setw(15)
    << "Score"
    << " |" << std::endl;

  std::cout << std::setfill('-') <<
    std::setw(40) << "-"
    << std::endl;

  std::cout << std::setfill(' ');

  std::cout << "| " << std::left <<
    std::setw(20) << "Alice"
    << "| " << std::right << std::setw(15) << 95
    << " |" << std::endl;

  std::cout << "| " << std::left <<
    std::setw(20) << "Bob"
    << "| " << std::right << std::setw(15) << 87
    << " |" << std::endl;

  std::cout << "| " << std::left <<
    std::setw(20)
    << "Charlie"
    << "| " << std::right << std::setw(15) << 92
    << " |" << std::endl;

  std::cout << std::setfill('-') <<
    std::setw(40) << "-"
    << std::endl;
}

This creates a neatly formatted table with alignedΒ columns.

----------------------------------------
| Name                |           Score |
----------------------------------------
| Alice               |              95 |
| Bob                 |              87 |
| Charlie             |              92 |
----------------------------------------

5. Progress Bars

You can create simple progress bars to show the status of long-runningΒ operations:

#include <iostream>
#include <thread>
#include <chrono>

void showProgress(int progress){
  int barWidth = 40;
  std::cout << "[";
  int pos = barWidth * progress / 100;
  for (int i = 0; i < barWidth; ++i) {
    if (i < pos) std::cout << "=";
    else if (i == pos) std::cout << ">";
    else std::cout << " ";
  }
  std::cout << "] " << progress << " %\r";
  std::cout.flush();
}

int main(){
  for (int i = 0; i <= 100; ++i) {
    showProgress(i);
    std::this_thread::sleep_for(
      std::chrono::milliseconds(50));
  }
}

This creates a progress bar that updates as an operationΒ progresses.

[==================>           ] 58 %

6. Using Unicode Characters

Modern terminals often support Unicode, allowing for more graphicalΒ elements:

#include <iostream>

int main(){
  std::cout <<
    "Simple shapes: ● β—‹ β–  β–‘ β–² β–³ β–Ό β–½\n";
  std::cout << "Card suits: β™  β™₯ ♦ ♣\n";
  std::cout << "Music notes: β™© β™ͺ β™« ♬\n";
  std::cout << "Arrows: ← ↑ β†’ ↓ ↔ ↕\n";
}

This displays various Unicode characters that can be used to enhance your consoleΒ output.

Simple shapes: ● β—‹ β–  β–‘ β–² β–³ β–Ό β–½
Card suits: β™  β™₯ ♦ ♣
Music notes: β™© β™ͺ β™« ♬
Arrows: ← ↑ β†’ ↓ ↔ ↕

Remember that the support for these formatting techniques can vary depending on the terminal or console application being used. Always test your application in the target environment to ensureΒ compatibility.

Additionally, consider providing fallback options for environments that don't support advanced formatting to ensure your application remains usable across differentΒ platforms.

This Question is from the Lesson:

User Input in the Terminal

This lesson introduces the fundamentals of capturing user input, using std::cin and std::getline

Answers to questions are automatically generated and may not have been reviewed.

This Question is from the Lesson:

User Input in the Terminal

This lesson introduces the fundamentals of capturing user input, using std::cin and std::getline

3D art showing a progammer setting up a development environment
Part of the course:

Intro to C++ Programming

Become a software engineer with C++. Starting from the basics, we guide you step by step along the way

Free, unlimited access

This course includes:

  • 59 Lessons
  • Over 200 Quiz Questions
  • 95% Positive Reviews
  • Regularly Updated
  • Help and FAQ
Free, Unlimited Access

Professional C++

Comprehensive course covering advanced concepts, and how to use them on large-scale projects.

Screenshot from Warhammer: Total War
Screenshot from Tomb Raider
Screenshot from Jedi: Fallen Order
Contact|Privacy Policy|Terms of Use
Copyright Β© 2024 - All Rights Reserved