This tutorial will guide you through the basics of using iostreams in C++. iostreams provide a convenient way to perform input and output operations in your programs.
Overview
- Input Streams: Used for reading data from various sources, such as the keyboard, files, or network sockets.
- Output Streams: Used for writing data to various destinations, such as the screen, files, or network sockets.
- Stream Operations: Various operations that can be performed on streams, such as reading, writing, formatting, and seeking.
Getting Started
Before you start, make sure you have a C++ compiler installed on your system. You can use any popular compiler like GCC or Clang.
Basic Syntax
#include <iostream>
int main() {
std::cout << "Hello, World!" << std::endl;
return 0;
}
In the above code, std::cout
is an output stream object that writes to the standard output (usually the screen). std::endl
is a manipulator that inserts a newline character and flushes the output buffer.
Reading Input
To read input from the user, you can use the std::cin
object, which is an input stream object.
#include <iostream>
int main() {
int number;
std::cout << "Enter a number: ";
std::cin >> number;
std::cout << "You entered: " << number << std::endl;
return 0;
}
In the above code, std::cin
is used to read an integer from the user and store it in the number
variable.
Writing Output
To write output to the screen, you can use the std::cout
object.
#include <iostream>
int main() {
std::cout << "This is a line of text." << std::endl;
return 0;
}
In the above code, std::cout
is used to write a line of text to the screen.
Formatting Output
You can format the output using various manipulators provided by the <iomanip>
header.
#include <iostream>
#include <iomanip>
int main() {
int number = 12345;
std::cout << "Number: " << std::setw(10) << number << std::endl;
return 0;
}
In the above code, std::setw(10)
is used to set the field width to 10 characters, and the number is left-aligned within the field.
More Information
For more information on iostreams, you can visit the C++ Standard Library documentation.