c++ read_ascii
#include <iostream>
#include <fstream>
#include <string>
int main() {
std::ifstream file("input.txt");
if (!file.is_open()) {
std::cout << "Failed to open the file." << std::endl;
return 1;
}
std::string line;
while (std::getline(file, line)) {
std::cout << line << std::endl;
}
file.close();
return 0;
}
Explanation:
#include <iostream>
: Includes the input/output stream library for handling input/output operations.#include <fstream>
: Includes the file stream library to perform input/output operations on files.#include <string>
: Includes the string library for handling strings.int main() { ... }
: The main function, the entry point of the program.std::ifstream file("input.txt");
: Declares an input file stream object namedfile
and opens a file named "input.txt" for reading.if (!file.is_open()) { ... }
: Checks if the file opening was unsuccessful. If the file failed to open, it displays a message indicating failure and returns 1 to indicate an error.std::string line;
: Declares a string variable namedline
to store each line of the file.while (std::getline(file, line)) { ... }
: Reads each line from the file usingstd::getline()
and stores it in theline
variable. The loop continues until there are no more lines to read.std::cout << line << std::endl;
: Prints each line read from the file to the standard output (console).file.close();
: Closes the file stream once reading is complete.return 0;
: Indicates successful execution of the program by returning 0 to the operating system.