"If a worker wants to do his job well, he must first sharpen his tools." - Confucius, "The Analects of Confucius. Lu Linggong"
Front page > Programming > How to Read All Data from Standard Input Until EOF in C++?

How to Read All Data from Standard Input Until EOF in C++?

Posted on 2025-03-24
Browse:520

How to Read All Data from Standard Input Until EOF in C  ?

Reading Data from Standard Input Until End-of-File in C

When working with data directly from user input in C , it's often desirable to read all data until the end-of-file (EOF) is reached. The cin.get() function allows for reading data until a specified character is encountered. However, using '\0' as the termination character may not be optimal as it doesn't truly represent EOF.

Using Loops for Data Extraction

The most effective solution for reading data until EOF involves the use of loops. The std::getline() function is particularly suitable for this purpose. By default, getline() reads data until a newline character is encountered. However, an alternative termination character can be specified:

std::string line;
while (std::getline(std::cin, line))
{
    std::cout 

In this example, getline() reads each line of data until the end-of-file is reached. The loop terminates when getline() fails to read any more data, indicating that EOF has been encountered.

Alternative Termination Character

Although EOF is not a character that can be specified directly, you can use a sentinel value to represent EOF. For instance, you can initialize a variable to a specific value and read data until that value is encountered:

const std::string EOF_MARKER = "EOF";
std::string line;
while (getline(std::cin, line))
{
    if (line == EOF_MARKER)
        break;

    std::cout 

This approach allows you to define your own end-of-file indicator, providing greater flexibility in your data processing.

Latest tutorial More>

Disclaimer: All resources provided are partly from the Internet. If there is any infringement of your copyright or other rights and interests, please explain the detailed reasons and provide proof of copyright or rights and interests and then send it to the email: [email protected] We will handle it for you as soon as possible.

Copyright© 2022 湘ICP备2022001581号-3