C++ input

C++ input

C++ input

In C++ input can be read from the console using the cin object, which is part of the iostream library. Here’s an example of how to use cin to read a value from the user:

				
					#include<iostream>
using namespace std;
int main() {
   int x;
   cout << "Enter a number: ";
   cin >> x;
   cout << "You entered: "<< x << endl; 
 return 0;

 }
				
			

In this example, the cin object is used to read a value from the user and store it in the variable x. The << operator is used to output the prompt message to the console, and the >> operator is used to read the value entered by the user.

Note that cin will only read input up to the first whitespace character (e.g., space, tab, newline). To read a whole line of input, use the getline function, like this:

				
					#include <iostream>
#include <string>
using namespace std;

int main() {
   string name;

   cout << "Enter your name: ";
   getline(cin, name);

   cout << "Hello, " << name << "!" << endl;

   return 0;
}

				
			

In this example, the getline function is used to read a line of input from the user and store it in the variable name. The << operator is used to output the prompt message to the console, and the getline function is used to read the whole line of input entered by the user. The getline function takes two arguments: the cin object and the variable to store the input in.

Join To Get Our Newsletter
Spread the love