C++ - console programming

Published: September 30, 2014

In Resources.

When learning C++ usually you are using console input/output from the start.

Example program which reads two values and displays sum of them:

#include <iostream>
using namespace std;

int main() {
    int a,b;
    cout << "Please enter first integer value: ";
    cin >> a;
    cout << "Please enter second integer value: ";
    cin >> b;
    cout << "a + b = " << (a+b) << endl;
    return 0;
}

Performance tips

To increase performance of stream output you can switch off synchronization with standard C output streams.

You can do this by executing at the start of program:

std::cout.sync_with_stdio(false);

It is also recommended to write end-of-line using "\n" instead of "endl" because the latter flushes buffer which slows down the program.

std::cout << "foo\n";       // fast
std::cout << "boo" << endl; // slow

See also

1) Introductory tutorials

2) Video tutorials

2) "Press any key to continue..." - Keep the console open long enough to see your program's output (cplusplus.com)

Tutorial how to wait for keyboard press in several ways.

3) Clear the screen - cplusplus.com

How to clear screen in several ways.

4) conio.h

conio.h is a non-standard console functions header for DOS/Windows

4) ANSI escape codes

Codes you can use to define color of text in console

5) TUI solutions

By TUI I mean advanced text interfaces that can present widgets (windows, buttons, checkboxes)

6) "How to handle Ctrl+C" in C++ & signals

Share

follow