1

I have some code and I wanted to use cin.eof() to stop my program from reading the input. I was thinking of doing:

char array[10]
while(!cin.eof())
{
  for(int i = 0; i < 10; i++)
  {
    cin >> array[i];
  }
}

And the code goes on. However, when I click '\n', my output is outputted. When i click cntrl + d, (on a UNIX terminal) the program performs the output again and then proceeds to end. How do I get it so that my program stops reading at a newline and prints my output when I type cntrl + d only once?

Thanks.

user1567909
  • 1,450
  • 2
  • 14
  • 24

1 Answers1

1

First, cin.eof() doesn't do anything useful until input has failed. You never want to use it at the top of a loop.

Secondly, it's not really clear to me what you are trying to do. Something like:

std::string line;
while ( std::getline( std::cin, line ) ) {
    //  ...
}

perhaps? This will read a line of text into the variable line, until end of file; when you encounter an end of file, the input will fail, and you will leave the loop.

James Kanze
  • 150,581
  • 18
  • 184
  • 329
  • What if I cant use strings? I've already constructed my program with char arrays – user1567909 Oct 15 '12 at 08:30
  • @user1567909 Then you'll have to use the member `istream::getline`, specifying a length, and looping or taking other action if the length is exceeded. In general, not using `string` for this sort of thing is a guaranteed way of making the code unnecessarily complex and fragile. – James Kanze Oct 15 '12 at 11:31