C++ Input and Output | cin, cout, endl vs \n, iomanip and File Streams
This complete tutorial on C++ Input and Output explains how to read input and display output in C++ programs. It covers the use of cin and cout, the difference between endl and \n, input/output formatting using the iomanip library, and the basics of file streams. The tutorial follows best coding practices and helps beginners write clean, readable, and efficient C++ programs.
Input and Output – Complete Tutorial
1. Input and Output in C++
C++ provides stream-based input and output using the <iostream> header.
Streams represent a flow of data from a source to a destination.
cin→ standard input (keyboard)cout→ standard output (console)
2. Using cin for Input
cin is used to read data from the standard input.
Example:
Multiple inputs:
Best Practices:
- Validate user input where required
- Use meaningful prompts
- Avoid mixing
cinwith C-style input (scanf)
3. Using cout for Output
cout is used to display output on the console.
Example:
Multiple outputs:
4. endl vs \n
Both endl and \n are used to insert a new line.
Using endl
Using \n
Difference:
| Featureendl\n | ||
| Inserts new line | Yes | Yes |
| Flushes output buffer | Yes | No |
| Performance | Slower | Faster |
Best Practice:
- Use
\nfor better performance - Use
endlonly when buffer flushing is required
5. Input/Output Formatting (iomanip)
The <iomanip> library is used to format input and output.
Common Formatting Functions:
setw
setprecision
left and right
setfill
Best Practices:
- Use formatting for reports and tables
- Reset formatting when required
- Avoid over-formatting simple output
6. File Stream Basics
C++ provides file handling using file streams from the <fstream> header.
File Stream Classes:
ifstream→ input from fileofstream→ output to filefstream→ input and output
Writing to a File
Reading from a File
Best Practices for File Handling:
- Always check if file opened successfully
- Close files after use
- Handle file errors gracefully
Example:
Common Mistakes to Avoid
- Forgetting to include
<iostream>or<fstream> - Using
endlexcessively - Not closing file streams
- Ignoring file open errors
Summary
In this chapter, you learned how to handle input and output in C++, including cin, cout, endl vs \n, output formatting using iomanip, and the basics of file streams. These concepts are essential for building interactive and file-based C++ applications.