For Example: If I need to read a multiple line input like(and I dont know How many lines would be there!!):
1 20
2 31
3 41
I am using something like
int main()
{
string line;
while(getline(cin,line) != NULL)
{
// some code
// some code
}
}
Now the program never stops- i.e always it expects some input. How do i beak the loop when there are no more input lines ?
Just insert a special end-of-input command, and parse the rest line-by-line. You can't automatically detect end-of-input, because there's no way to know if the user is genuinely finished inputting or just browsing or speaking or whatever- it's a totally system-external circumstance.
Note that the use of scanf directly on stdin is not very safe. For example, entering anything that can't be parsed as a number will make the loop hang. Here's a more robust implementation that reads whole lines first and then tries to parse the numbers from it.
Just test the variable
line
for empty each time you read a line. If the use presses enter with no other data, thenline
will be empty.On linux - C-d (or Ctrl+D) outputs the EOF character, which will terminate your loop.
It's much easier to do something like...