How to read an unknown quantity of integers from console?

I have entries like these:

0 5 260
1 0 -598
1 5 1508
2 1 -1170

I don't know previously how many (console) inputs I'll get, so I have to read until there are no entries left.

I started with a code like this:

int a, b, c;
while(scanf("%d %d %d", &a, &b, &c)!=EOF){
    // do stuff here
}

But it never stops asking for new input.

Then, I saw people in other threads suggesting this:

int a, b, c;
while(scanf("%d %d %d", &a, &b, &c)==1){
    // do stuff here
}

In this case, it doesn't even enter the while.

Does anyone know what I'm doing wrong?

Answers


An approach: Continue asking for input until the input is closed (EOF) or some problem is encountered. (Invalid line of input)

The below uses fgets() to read a line.

Then, " %n" to detect where scanning stopped. If scanning does not reach %n, n will still have the value of 0. Otherwise it gets the offset in buffer where scanning stopped, hopefully it was at the null character '\0'.

char buffer[100];
while (fgets(buffer, sizeof buffer, stdin)) {
  int n = 0;
  sscanf(buffer, "%d%d%d %n", &a, &b, &c, &n);
  if (n == 0) {
    fprintf(stderr, "3 int were not entered\n");
    break;
  }
  if (buffer[n] != 0) {
    fprintf(stderr, "Extra input detected.\n");
    break;
  }
  // do stuff here with a,b,c
}

There are many approaches to solve this issue.


while(scanf("%d %d %d", &a, &b, &c)==1)

means that "if scanf() successfully read just one value, proceed in the loop."

Therefore, if you enter something like 0 junk, the scanf() read just 1 data and will enter the loop once.

Try using

while(scanf("%d %d %d", &a, &b, &c)==3)

to have it enter the loop when scanf() successfully read three values, which is what expected.


Need Your Help

How to add some contents in pom.xml for "mvn install"?

java maven pom.xml

I have multiple java projects with me. I have one document to Build the source code using Maven. I am following it and trying to build the project.

Handlebars won't loop over my Backbone.js Collection

javascript json backbone.js handlebars.js

I have a Backbone app where I'm attempting to populate a collection using a JSON file. I want to generate a list of "titles" from the JSON to eventually turn into a menu.