Input and Output in C++
Certainly, let's explore input and output operations in C++.
1. Input
* Standard Input (stdin):
* Typically refers to the keyboard.
* The most common way to get input from the user is using the cin object.
#include <iostream>
int main() {
int number;
std::cout << "Enter an integer: ";
std::cin >> number;
std::cout << "You entered: " << number << std::endl;
return 0;
}
* Other Input Streams:
* You can read input from files using the ifstream class.
* Example:
#include <iostream>
#include <fstream>
int main() {
std::ifstream myfile("data.txt");
if (myfile.is_open()) {
std::string line;
while (getline(myfile, line)) {
std::cout << line << std::endl;
}
myfile.close();
} else {
std::cout << "Unable to open file" << std::endl;
}
return 0;
}
2. Output
* Standard Output (stdout):
* Usually refers to the console or terminal.
* The cout object is used to display output on the screen.
#include <iostream>
int main() {
std::cout << "Hello, world!" << std::endl;
return 0;
}
* Other Output Streams:
* You can write output to files using the ofstream class.
* Example:
#include <iostream>
#include <fstream>
int main() {
std::ofstream myfile("output.txt");
if (myfile.is_open()) {
myfile << "This is a line of text.\n";
myfile.close();
} else {
std::cout << "Unable to open file" << std::endl;
}
return 0;
}
Key Concepts
* iostream Library: The iostream library provides the basic tools for input and output in C++.
* Objects: cin, cout, ifstream, and ofstream are objects that represent input and output streams.
* Stream Operators:
* << is the insertion operator (used with cout) to send data to the output stream.
* >> is the extraction operator (used with cin) to get data from the input stream.
Example: Reading and Writing to a File
#include <iostream>
#include <fstream>
int main() {
std::ifstream inputFile("input.txt");
std::ofstream outputFile("output.txt");
if (inputFile.is_open() && outputFile.is_open()) {
int number;
while (inputFile >> number) {
outputFile << number * 2 << std::endl;
}
inputFile.close();
outputFile.close();
} else {
std::cout << "Error opening files." << std::endl;
}
return 0;
}
This example reads numbers from "input.txt", multiplies each number by 2, and writes the results to "output.txt".
I hope this explanation is helpful! Let me know if you have any further questions.
Comments
Post a Comment