C++ Basic Input and Output

In the world of programming, input and output are the essential mechanisms through which a program communicates with the external environment. Input refers to data provided to the program, while output is the result or response produced by the program.

In this tutorial we learn about basic input and output capabilities provided by C++ programming language. For Input and output, C++ programming language uses an abstraction called streams which are sequences of bytes. A stream is an abstract entity where a program can either write or read characters. It hides the hardware implementation and details from the C++ program.

In any input operation, data from mouse, keyboard, external disk etc to main memory for program consumption whereas data flows from main memory to output devices like screen, printer etc, in any output operation. In most programming environments, standard input device by default is keyboard and standard output device by default is screen. The C++ standard library defines some stream objects for input and output.

Standard Input Stream (cin)

cin is a predefined object of class istream. cin object by default is attached to the standard input device which is keybord in most programming environments. cin along with extraction operator (>>) is used to take keyboard input from user. Extraction operator is followed by a variable where the input data is stored. cin is an input statement, hence programs waits for user to enter input from keyboard and press enter. Input data flows directly from keyboard to variable.

Here is an example of reading an integer value from user
int count;
cin >> count;
Here is an example of reading an integer value from user
int count, sum;
cin >> count >> sum;

Based on the data type of the variable after extraction operator(>>) cin determine how it interprets the characters read from the input. If the variable is of integer data type than it will expect integer input from user.
We can also take string input from user using cin and extraction operator. For string input, it reads characters till first white space character(space, tab, newline etc). With cin we can only read one word at a time, it does not support reading an entire line having space characters. To read an entire space seperated sentence we should use "getline" function.


Standard Output Stream (cout)

cout is a predefined object of class ostream. cout object by default is attached to the standard output device which is screen in most programming environments. cout along with insertion operator (<<) is used to display data to user on screen. Insertion operator is followed by a variable or constant which needs to be displayed to user. Input data flows directly from variable to output stream.

Here is an example of printing an integer on screen
int count = 10;
cout << count;
We can print multiple values at a time by cascading insertion operator.
cout << count << 20 << "Hello";
We can use ‘\n‘ or endl to print the output on new line.
cout << 20 << endl << "Hello\n" << "World";
Output :
20
Hello
World

C++ Program for Basic Input Output using cin and cout

#include <iostream>
using namespace std;
 
int main( ) {
   char name[50];
   int age, salary, account_number;
 
   cout << "Enter your name \n";
   // reading string 
   cin >> name;
   cout << "Enter your age \n";
   // reading integer
   cin >> age;
   cout << "Enter your salary and account number\n";
   // taking two input at a time 
   cin >> salary >> account_number;
   
   cout << name << endl << age << endl <<
        salary << endl << account_number;
   
   return 0;
}
Output
Enter your name
Adam
Enter your age
22
Enter your salary and account number
2345 87654
Adam
22
2345 
87654
In above program, we are taking input from user using cin and printing it on screen using cout as explained above. We are taking input of different data types like integer and string. We are also taking multiple inputs in a single cin statement by using multiple extraction operator.

File Input and Output in C++

Beyond console input and output, C++ supports file input and output operations. This allows you to read from and write to external files. Let's explore a basic example of writing and reading from a file:
  • File Output (ofstream)
    #include <iostream>
    #include <fstream>
    
    int main() {
        std::ifstream inputFile("output.txt");
    
        if (inputFile.is_open()) {
            std::string line;
    
            while (getline(inputFile, line)) {
                std::cout << line << std::endl;
            }
    
            inputFile.close();
        } else {
            std::cout << "Unable to open the file." << std::endl;
        }
    
        return 0;
    }
    
    In this example, an ofstream (output file stream) named outputFile is created. The file "output.txt" is opened, and two lines of text are written to it. Finally, the file is closed.

  • File Input (ifstream)
    #include <iostream>
    #include <fstream>
    
    int main() {
        std::ifstream inputFile("output.txt");
    
        if (inputFile.is_open()) {
            std::string line;
    
            while (getline(inputFile, line)) {
                std::cout << line << std::endl;
            }
    
            inputFile.close();
        } else {
            std::cout << "Unable to open the file." << std::endl;
        }
    
        return 0;
    }
    
    In this example, an ifstream (input file stream) named inputFile is created to read from the file "output.txt." The program reads the file line by line using getline and prints each line to the console.

Conclusion

Congratulations! You've now explored the fundamentals of input and output in C++. From basic console interactions to handling different data types and even reading from and writing to files, you've gained a solid understanding of how to make your C++ programs interactive and dynamic.

As you continue your programming journey, remember that effective input and output handling is a key aspect of creating robust and user-friendly applications. Whether you're building console-based tools or developing graphical user interfaces, the principles you've learned here will serve as a strong foundation.