Your problem is almost the same as the one outlined in this other question. The only difference is that yours is in C, not Java.
The solution approach is the same. You are reading lines containing numbers. This is different from simply reading numbers. Although they are similar things, there is some difference exactly because of the line breaks. So, to read a line containing a number, do so:
char linha[11];
fgets(linha, 10, stdin); // Lê a linha inteira.
sscanf(linha, "%d", &y); // Retira o número da linha lida.
To remove three numbers from the read line:
sscanf(linha, "%d %d %d", &a, &b, &c); // Retira três números da linha lida.
To read multiple numbers from a line and process them as we read, it gets more complicated, but we can use the %n
which tells how many characters were read. For example:
#include <stdio.h>
int main(void) {
char linha[10001];
fgets(linha, 10000, stdin); // Lê a linha inteira.
int pos = 0;
while (1) {
int y;
int p;
int ret = sscanf(&linha[pos], "%d%n", &y, &p); // Retira um número da linha lida.
pos += p;
if (ret == EOF) break;
printf("%d ", y);
}
printf("fim");
}
With this input:
1 2 3 4 5 6 7 8
That’s the way out:
1 2 3 4 5 6 7 8 fim
See here working on ideone.
These four lines are the heart of the business:
int p;
int ret = sscanf(&linha[pos], "%d%n", &y, &p); // Retira um número da linha lida.
pos += p;
if (ret == EOF) break;
First, the %d
will put the read value in the address of y
. This if any value can be read. If no value can be read, EOF
is returned and the break;
interrupts the while
.
If any value can be read, the %n
specifies that the amount of characters read is placed at the address of p
. This is then added to the value of pos
. In this way, &linha[pos]
always share the not yet read part of the line.
The input can be
2 3 4
or just2
if you enter, that’s it?– Fábio Morais
Yes, I can type 2 3enter, or 2enter.
– William Philippe
Your error is almost the same: https://answall.com/q/262976/132 - Only yours is in C instead of Java.
– Victor Stafusa