-1

I was asked a question to write a function which takes and returns an istream&. The function should read the stream until it hits EOF and the value read should be printed with standard output.

Here is my code which works nearly fine:

#include<iostream>
#include<string>
#include<istream>


std::istream& fun(std::istream &ob)
{
    std::string s;
    while((ob>>s)&&(!ob.eof()))
        std::cout<<s<<'\n';
    return ob;
}

int main()
{
    std::istream &obj = fun(std::cin);
    return 0;
}

The only part which is not happening is program (istream) reaching to EOF - I have to manually enter ctrl + d on the terminal to stop the loop - is there any other way around to do this?

Agrudge Amicus
  • 1,033
  • 7
  • 19
  • 1
    I'm confused what precisely your question. Your function implements the functionality described in your first paragraph. Do you want it terminate **before** `EOF` instead? Or are you asking if there is an alternate way to send an `EOF` from your shell? – Brian61354270 Apr 03 '20 at 22:29
  • Almost Duplicate: https://stackoverflow.com/questions/16136400/how-to-send-eof-via-windows-terminal – user4581301 Apr 03 '20 at 22:32
  • 4
    Note: `while((ob>>s)&&(!ob.eof()))` is a bit more than necessary. Detection of EOF is covered by testing `ob>>s`. – user4581301 Apr 03 '20 at 22:36

2 Answers2

4

That's expected.

Ctrl+D is how you signal EOF.

Otherwise how would the terminal know that you wish to stop providing input? Where would EOF actually be?

Asteroids With Wings
  • 17,071
  • 2
  • 21
  • 35
3

That is the expected behavior.

Assuming you're in a Unix-y environment, you could alternatively pipe input to your program's stdin via redirection from the shell:

$ ./my_program < ./some_file.txt

Or, for the cat abusers,

$ cat ./some_file.txt | ./my_program

This is essentially equivalent to executing my_program and then manually typing out the contents of some_file.txt followed by CTRL+D.

Brian61354270
  • 8,690
  • 4
  • 21
  • 43