Home | About | Categories | All Tips & Tutorials

Basic user input and output using C++ in Linux, Learning C++

ID: 234

Category: C++

Added: 19th of December 2020

Updated On: Tutorial updated and rechecked on 21st of November 2024

Views: 2,940



Click here to buy Linux C++ books on Amazon
Affiliate Link ⓘ

The following script in C++ asks the user to enter their name and age and then displays the results.
Two variables are created, string to store the name, and int (integer) to store the age.

Create a new file, then copy and paste the code below. Save the file as inputoutput.cpp

#include <iostream>
using namespace std;

int main()
{
string name;
int age;

cout << "What is your name? ";
cin >> name;
cout << "How old are you? ";
cin >> age;

cout << "Hello " << name << " you are " << age << " years old\n";
return 0;
}

Next we need to compile and create an executable file.
Open your terminal and enter the following command
g++ inputoutput.cpp -o inputoutput

To run the script
./inputoutput