#include <iterator>
#include <iostream>
using namespace std;
const int MAX_NAME_LENGTH=100;
int main()
{
char name[MAX_NAME_LENGTH];
cout<<"Introduce yourself\n";
istream_iterator<char> eos;
istream_iterator<char> isi(cin);
for(int i=0;i<MAX_NAME_LENGTH; i++)
{
if(isi == eos)
{
name[i]=0; //Breakpoint is set here.
break;
}
name[i] = *isi;
isi++;
}
cout<<"Hi "<<name<<endl;
system("pause");
}
When I type a name and press enter, this program still yields only a command prompt. After debugging, it turned out that the “if” is never reached; It seems to be that the end of stream (eos) is unreachable.
- Why the condition inside the “if” is always false?
- What is the simpliest way to fix my problem?
The condition is satisfied when the end of file is reached, but the console has no natural EOF, so you need to tell it explicitly where the end is. You can enter the EOF character to the console by pressing ctrl+z in Windows or ctrl+d in Unix. Here’s a sample run that works:
Input
Output