Writing console application
In this section
This tutorial describes the basic steps that you must complete to create and run a console application from the command line.
Create console
The following procedures describe the basic steps that you must complete to create and run a console application from the command line.
To create the console
- Create console1.cpp file in your project folder and type the following include file and using statements:
#include <xtd/xtd>
using namespace xtd;
- Declare a class named console1.
class console1
- Create a default constructor for console1.
You will add more code to the constructor in a subsequent procedure.
public:
console1() {}
- Add a main method.
Create an instance of the console1.
auto main() -> int {
console1 {};
}
To create the CMakeLists.txt
- Create CMakeLists.txt file in your project folder and add the cmake minimum version required.
cmake_minimum_required(VERSION 3.20)
- Set the project name and add xtd.forms package.
Project(console1)
find_package(xtd REQUIRED)
- Add build rules for the he project.
add_sources(console1.cpp)
target_type(CONSOLE_APPLICATION)
To compile and run the application
At the Terminal, navigate to the directory you created the console1.cpp class and CMakeLists.txt file.
Compile the console.
xtdc build
- At the command prompt, type:
xtdc run
Adding a write line and read line
The previous procedure steps demonstrated how to just create a basic console that compiles and runs.
To change background and foreground colors and write and read line with the console
- Change background color
- Change foreground color
- Write desired text to the console.
- Ask user and write result in name.
- Write formatted result to the console.
The following code example demonstrates how to write and read with the console.
console1() {
console::background_color(console_color::blue);
console::foreground_color(console_color::white);
console::write_line("What's your name ?");
auto name = console::read_line();
console::write_line("Hello, {}", name);
}
- Compile and run the application.
xtdc run
Example
Following code example is the complete example from the previous tutorial.
console1.cpp:
#include <xtd/xtd>
using namespace xtd;
class console1 {
public:
console1() {
console::background_color(console_color::blue);
console::foreground_color(console_color::white);
console::write_line("What's your name ?");
auto name = console::read_line();
console::write_line("Hello, {}", name);
}
};
auto main() -> int {
console1 {};
}
CMakeLists.txt:
cmake_minimum_required(VERSION 3.20)
project(console1)
find_package(xtd REQUIRED)
add_sources(console1.cpp)
target_type(CONSOLE_APPLICATION)