In C++, cout is used to print the instruction and show it on the console window . cout does the same thing as printf does in C.The proper syntax for cout requires << operator [ cout<<] for displaying the output and in case you forget to do so you will face syntax error.
Similarly the concept of cin is relatable to the scanf used in C language. Cin is used to take the data from the user , the entered data is stored in the memory loaction and the code reacts with respect to that. The proper syntax for cin requires >>operator [ cin>>].
Example 1: String Output
#includeusing namespace std; int main() { // prints the string enclosed in double quotes cout << "GRATITUDE"; return 0; }
Output:
GRATITUDE
Working of this program
" "
. It is followed by
the <<
operator#include <iostream> int main() { // prints the string enclosed in double quotes std::cout << "GRATITUDE"; return 0; }
Example 2: Numbers and Characters Output
#include <iostream> using namespace std; int main() { int number1 = 33; double number2 = 129.254; char ch = 'G'; cout << num1 << endl; // print integer cout << num2 << endl; // print double cout << "character: " << ch << endl; // print char return 0; }
Output:
33 129.254 character: G
Note:
For example:
cout << "character: " << ch << endl;
Example 3: Integer Input/Output
#include <iostream> using namespace std; int main() { int number; cout << "Enter integer: "; cin >> number; // Taking input cout << "digit is: " << number; return 0; }
Output:
Enter integer: 2500 digit is: 2500
In the program, we used
cin >> number;
to take input from the user. The input is stored in the variable number . We use the >> operator with cin to take input.
Example 4: C++ Taking Multiple Inputs
#include <iostream> using namespace std; int main() { char p; int number; cout << "Enter a character and an integer: "; cin >> p >> number; cout << "Character: " << p << endl; cout << "digit: " << number; return 0; }
Output:
Enter a character and an integer: D 64 Character: D digit: 64