Input and Output in C++: Console, Files, and Basic Graphics
Learn how to interact with users through the console, read and write files, format output with manipulators, and get an introduction to graphics programming in C++.
- How to use cin and cout for console input/output
- How to format output using manipulators
- How to read from and write to text files
- How to handle file errors properly
- Basic concepts of graphics in C++
1Console input and output
C++ uses cin and cout from the <iostream> library for standard input and output. These are the most basic tools for interacting with the user through the terminal.
How it works:
coutdisplays messages or data to the terminalcinreads input from the user<<is the insertion operator (used withcout)>>is the extraction operator (used withcin)
Example:
#include <iostream> using namespace std; int main() { int age; cout << "Enter your age: "; cin >> age; cout << "You entered: " << age << endl; return 0; }
2Inputting multiple values
You can chain cin to read multiple inputs in a single line. The user can enter values separated by spaces or newlines.
int a, b; cin >> a >> b; cout << "a = " << a << ", b = " << b << endl;
getline(cin, name) instead of cin >> name. The extraction operator stops at whitespace.
3Formatting output
C++ provides the <iomanip> library for formatting output. These manipulators give you control over how numbers and text are displayed.
| Manipulator | Use |
|---|---|
setw(n) | Sets width of output |
setprecision(n) | Controls decimal places |
fixed | Uses fixed-point notation |
left, right | Aligns text |
Example – formatting a decimal number:
#include <iostream> #include <iomanip> using namespace std; int main() { double pi = 3.14159265; cout << fixed << setprecision(2) << pi << endl; return 0; }
Example – setting width and alignment:
cout << setw(10) << "Hello" << endl; cout << left << setw(10) << "World" << endl;
4Reading and writing files
To perform file I/O in C++, include the <fstream> library. This gives you:
ofstream– for writing to filesifstream– for reading from filesfstream– for both reading and writing
Writing to a file
#include <fstream> using namespace std; int main() { ofstream outFile("output.txt"); if (outFile.is_open()) { outFile << "Hello, file!" << endl; outFile << "This is written using C++." << endl; outFile.close(); } return 0; }
This creates a file named output.txt and writes two lines to it.
Reading from a file
#include <fstream> #include <iostream> #include <string> using namespace std; int main() { ifstream inFile("output.txt"); string line; if (inFile.is_open()) { while (getline(inFile, line)) { cout << line << endl; } inFile.close(); } return 0; }
5File check and error handling
Always check whether a file is open before using it. This prevents crashes and helps you debug issues.
ifstream file("data.txt"); if (!file) { cout << "Error opening file." << endl; return 1; } // Proceed with reading...
close() explicitly. This ensures all data is written and resources are freed.
6Simple graphics in C++ (intro)
C++ itself does not have built-in graphics. To create graphical applications, you need to use external libraries like:
- SFML – Simple and Fast Multimedia Library
- SDL – Simple DirectMedia Layer
- graphics.h – Older library used with Turbo C++ (mostly legacy)
Here is a simple program using graphics.h (note: this only works in certain environments like Code::Blocks with proper setup):
#include <graphics.h> int main() { int gd = DETECT, gm; initgraph(&gd, &gm, ""); circle(200, 200, 100); // draw circle at x=200, y=200, radius=100 getch(); closegraph(); return 0; }
7Common mistakes to avoid
<fstream> for file I/O and <iomanip> for formatting. Without them, you will get compilation errors.
if (!file) before reading or writing. This prevents crashes when the file does not exist or cannot be accessed.
cin >>, the newline character stays in the input buffer. When you then use getline(), it will read that newline as an empty line. Use cin.ignore() to clear the buffer.
8Mini exercises
- Ask the user to enter their name and age, and print a message like:
Hello Sarah, you are 21 years old. - Create a program that writes 5 numbers to a file, one per line.
- Write a program to read numbers from a file and print their sum.
- Write a program that asks the user for a number and prints it with 3 decimal places using
setprecision.
Hint: For reading numbers from a file, use a loop with file >> num and add to a running total.
