Read until first period

Read until first period.

Create a program that reads the contents of a file named example.txt until a period ('.'), is encountered. The program should then print the content read so far to the console. If the specified character is not found, it should print the entire content of the file.

Answer

#include <iostream>
#include <fstream>

int main() {
    std::ifstream inFile("example.txt");

    if (!inFile) {
        std::cerr << "Error: Could not open the file example.txt." << std::endl;
        return 1;
    }

    char ch;
    char stopChar = '.';
    std::cout << "Reading file until '" << stopChar << "' is encountered:" << std::endl;

    while (inFile.get(ch)) {
        std::cout << ch;
        if (ch == stopChar) {
            break;
        }
    }

    if (inFile.eof()) {
        std::cout << std::endl << "End of file reached without encountering '" << stopChar << "'." << std::endl;
    }

    inFile.close();
    return 0;
}
Questions