C++ User Input

In C++, you can read input from the user using the standard input stream "cin". The "cin" object is defined in the "iostream" library, so you need to include this library at the beginning of your program:

#include <iostream>
using namespace std;

To read input from the user, you can use the ">>" operator to extract data from the standard input stream:

int age;
cout << "Enter your age: ";
cin >> age;

In this example, we declare an integer variable named "age", and then use the ">>" operator to read an integer value entered by the user from the standard input stream. The prompt "Enter your age: " is displayed using the "cout" object.

You can also read input of other types, such as floating-point numbers and characters:

double salary;
cout << "Enter your salary: ";
cin >> salary;

char initial;
cout << "Enter your middle initial: ";
cin >> initial;

In these examples, we read a floating-point value entered by the user into the variable "salary", and a character entered by the user into the variable "initial".

Note that when using "cin" to read input, the user must enter data that matches the expected type, otherwise the input operation may fail. You can use error handling to handle input errors and prevent the program from crashing:

int age;
cout << "Enter your age: ";
if (!(cin >> age)) {
  // Handle input error
}

In this example, we use an "if" statement to check if the input operation succeeded. If the input was not an integer, the condition will be false and the code inside the "if" block will be executed to handle the input error.

Comments

Leave a Reply

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

30456