C++ is another programming language that extends the abilities of C. Essentially, it is an object oriented version of C. C commands can be used in C++, but C++ has commands that are not available in C. One example of these commands are the input and output commands cin and cout. They are part of the library iostream.
cout sends text and the value of variables to the output stream. By default, the output stream is the data that is displayed in the console. cin reads data from the input stream. By default, this stream is stdin, the data input from the keyboard.
Both commands rely on the redirection characters << and >> to either send data to the output stream or pull data from the input stream. The format for cout is:
cout << arg1 << ... << argN;where arguments arg1 through argN are either variables whose value should be displayed, strings or control characters. endl is the control character that causes the output to move to the next line.
The syntax for cin is very similar, except the redirection arrows point in the opposite direction because data is being routed from the input stream to the variables where it is to be stored. The format for cin is:
cin >> arg1 >> arg2 ... >> argN;where arguments arg1 to argN are the names of variables where the data is to be stored.
The syntax of cin and cout is cimpler than printf and scanf, but cout and cin are only available in C++, not C.
The program below provides an example of using cin and cout. A sample run of the program showing user data and the output is given below the code listing.
#includeint main(int argc, char* argv[]) { int dec; char string[32]; //display a text message and move to the next line //This command sends the data to the output stream cout << "Enter an integer number and a string" << endl; //read in the users data from the input stream cin >> dec >> string; //Display a message made up of two strings and the users data cout << "ha ha! You entered the number " << dec << " and the string " << string << ". Thanks for playing!"<< endl; return 0; }
Output from a sample program run:
Enter an integer number and a string 45 happy ha ha! You entered the number 45 and the string happy. Thanks for playing!