plethora
plethora

Reputation: 135

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?

Upvotes: 2

Views: 114

Answers (2)

chux
chux

Reputation: 153602

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.

Upvotes: 1

MikeCAT
MikeCAT

Reputation: 75062

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.

Upvotes: 0

Related Questions