C++ Basic User Input and Output

With the help of examples, we will learn how to use the cin object to receive user input and the cout object to display output to the user in this tutorial. The libraries that come with C++ give us a variety of options for performing basic user input and output. Input and output in C++ are carried out using streams, which are simply a series of bytes.

Basic User Input and Output-banner

C++ Output

To output values or print text, use the cout object and the << operator:

Example:

#include <iostream>
using namespace std;
int main() {
  cout << "Hello GeektoCode!\n";
  cout << "I am learning C++ By GeektoCode";
  return 0;
}

OUTPUT:

Basic User Input and Output-pic3

As many cout objects as you like may be added. However, observe that it does not add a new line to the output’s end

C++ User Input

You are already aware of how to output (print) values using cout. To gather user input, we will now use cin.

The extraction operator (>>) is used to read data from the keyboard into the predefined variable cin.

The user can enter a number in the example below, and that number will be stored in the variable y. The value of y is then printed:

Example:

#include <iostream>
using namespace std;
int main() {
int y; 
cout << "Type a number: "; // Type a number and press enter
cin >> y; // Get user input from the keyboard
cout << "Your number is: " << y; // Display the input value
return 0;
}

OUTPUT:

Basic User Input and Output-pic2
Know This: The word "cout" is pronounced "see-out." it uses the insertion operator () and is used for output.
"See-in" is how you pronounce cin. utilizes the extraction operator (>>) and is used as input.

Creating a Basic Calculator

The user is required to enter two numbers in this example. Then, after computing (adding) the two numbers, we print the sum:

#include <iostream>
using namespace std;
int main() {
int x, y;
int mul;
cout << "Type a number: ";
cin >> x;
cout << "Type another number: ";
cin >> y;
mul = x * y;
cout << "multiplication is: " << mul;
return 0;
}

OUTPUT:

Basic User Input and Output-pic
Note: We must use std::cout rather than cout if the using namespace std; statement is missing.
This approach is preferred because using the std namespace might lead to issues.
To make the tutorials' codes more readable, we have however used the std namespace.
#include <iostream>
int main() {
    // prints the string enclosed in double quotes
    std::cout << "This is C++ Programming";
    std::cout << "GeektoCode.com";
    return 0;
}

OUTPUT

Basic User Input and Output-pic1

Leave a Reply

Your email address will not be published. Required fields are marked *