Home >Backend Development >C++ >How Can I Read stdin Until EOF in C Without Explicit Loops?

How Can I Read stdin Until EOF in C Without Explicit Loops?

Susan Sarandon
Susan SarandonOriginal
2024-11-17 04:01:03823browse

How Can I Read stdin Until EOF in C   Without Explicit Loops?

Capturing Input from stdin Until EOF without Loops

Reading input from standard input until the end-of-file (EOF) is a common task in C programming. Typically, loops are employed to achieve this, but in certain situations, a non-looping approach may be desirable.

Solution Without Loops

Unfortunately, there is no single, non-looping function in C that can read input from stdin until EOF. However, combining input operators and C string manipulation offers a workaround:

char input[1000];
cin.getline(input, 1000);
while (cin.eof() == false) {
    cout << input << endl;
    cin.getline(input, 1000);
}

This approach uses cin.getline() to read a maximum of 1000 characters from stdin into the input array. It then checks if EOF has been reached using cin.eof(). If not, it prints the input to the console and repeats the process until EOF is encountered.

Best Loop-Based Approach

If a non-looping solution is not feasible or desirable, the best loop-based approach is to use the std::getline() function:

string line;
while (getline(cin, line)) {
    // Process the line
}

This approach enters a loop that reads lines of input using getline() until the end of file is reached. getline() returns false when input fails or EOF is encountered, causing the loop to terminate.

The above is the detailed content of How Can I Read stdin Until EOF in C Without Explicit Loops?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn