C++ Console I/O




Since C++ is a superset of C, all elements of the C language are also contained in the C++ language. Therefore, it is possible to write C++ programs that look just like C programs. There is nothing wrong with this, but to take maximum benefit from C++, you must write C++-style programs.

This means using a coding style and features that are unique to C++.

The most common C++-specific feature used is its approach to console I/O. While you still can use functions such as printf( ) and scanf( ), C++ I/O is performed using I/O operators instead of I/O functions.

The output operator is <<. To output to the console, use this form of the
<< operator:
      cout << expression;

where expression can be any valid C++ expression, including another output expression.

cout << "This string is output to the screen.\n"; cout << 236.99; The input operator is >>. To input values from keyboard, use
cin >> variables;

Example:
#include < iostream >
using namespace std;
int main( ) {
// local variables int i; float f;
// program code 
cout << "Enter an integer then a float "; // no automatic newline cin >> i >> f; // input an integer and a float

cout << "i= " << i << " f= " << f << "\n";  // output i then f and newline return 0; } 

You can input any items as you like in one input statement. As in C, individual data items must be separated by whitespace characters (spaces, tabs, or newlines). When a string is read, input will stop when the first whitespace character is encountered. 



Post a Comment

0 Comments