cin

Acquires input from stdin, usually the (console's) keyboard.

 

C++ uses the cin object defined with the standard namespace of the <iostream> header file.

 

cin is the name given to the standard input stream stdin.

 

Used with the >> stream extraction operator to send the incoming entered stream from stdin to a specified variable.

 

Closed with a semi-colon ;

 

A major difference to C’s scanf() function.

 

#include <iostream>
using namespace std ;

int main () {

	char yourName[20] ;

	cout << "Please enter your first name:" << endl;
	cin >> yourName ;

	cout << "You entered: " << yourName << endl ;

	return 0;
}

Compile & Run:

Please enter your first name:Gomez 

You entered: Gomez

 

 

Or getting more than one value, as per line 10:

#include <iostream>
using namespace std ;

int main () {

	char yourName[20] ;
	int age ;

	cout << "Please enter your first name, and your age:" << endl;
	cin >> yourName >> age;

	cout << "You entered your name as: " << yourName << " and your age as: "<< age << endl ;

	return 0;
}

Compile & Run:

Please enter your first name, and your age:
Harriette
33
You entered your name as: Harriette and your age as: 33

 

 

*Note: that cin stops reading the input stream as soon as it reaches the first blank space character.

 

To acquire a whole sentence, including blanks, the getline() function is preferred:

#include <iostream>
using namespace std ;

#include <string>

int main () {

	string favBand ;

	cout << "Please enter the name of your favourite band:" << endl ;

	getline(cin, favBand) ;

	cout << "Yeah, " << favBand << " Rock!" << endl ;

	return 0;
}

Compile & Run:

Please enter the name of your favourite band:
The Fall
Yeah, The Fall Rock!

Leave a Reply