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 test the variable line
for empty each time you read a line. If the use presses enter with no other data, then line
will be empty.
#include <iostream>
#include <string>
using std::cin;
using std::getline;
using std::string;
int main(int argc, char *argv[]) {
string line;
while (true) {
getline(cin, line);
if (line.empty()) {
break;
}
// some code
}
return 0;
}
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.
#include <stdio.h>
#include <stdlib.h>
int main(void) {
char * line = NULL;
size_t sz = 0;
while(!feof(stdin)) {
ssize_t ln = getline(& line, & sz, stdin);
if(ln > 0) {
int x, y;
if(sscanf(line, "%d %d", & x, & y) == 2)
printf("x = %i, y = %i\n", x, y);
else
puts("invalid input");
}
}
return EXIT_SUCCESS;
}
On linux - C-d (or Ctrl+D) outputs the EOF character, which will terminate your loop.
It's much easier to do something like...
~ $ cat sample.input | my_cool_program
output will be displayed here.
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.
while (true)
{
long value1;
long value2;
int nofValuesRead;
nofValuesRead = scanf("%ld %ld\n",&value1,&value2);
if (nofValuesRead==0) break;
if (nofValuesRead>=1)
{
// Process value1
}
if (nofValuesRead>=2)
{
// Process value2
}
}