#include#include void readFromFile() { std::ifstream file("example.txt"); std::string line; while (getline(file, line)) { // do something with the line } file.close(); }
#includeIn this example, we open the file "example.txt" and check if it opened successfully. If not, we print an error message and exit the program. We then use getline to read the first line of the file and print it to the console. Overall, the ifstream getline function is a useful tool for reading lines of text from a file in C++.#include #include int main() { std::ifstream file("example.txt"); if (!file.is_open()) { std::cout << "Error opening file\n"; return 1; } std::string line; getline(file, line); std::cout << "First line of file: " << line << "\n"; file.close(); return 0; }