Originally Posted by
JohnGM
Hi ..
WoodSTokk........we can all make smart comments.....I am here to learn.....I am looking for your contribution but can't find it..?
John
Ops. I realy think thats a joke. Sorry.
To the problem.
The format "%d%d%d%d%d" expect 5 numbers in a row without delimiter.
Asume we enter "1234567890". What numbers will scanf read in the variables?
It can be 1, 2, 3, 4 and 567890 ... or 123456, 7, 8, 9 and 0 ... nobody knows.
It is better to use a delimiter.
In this example, i use space as delimiter:
Code:
…
scanf(" %d %d %d %d %d", &x[0], &x[1], &x[2], &x[3], &x[4]);
…
Asume we enter "12 34 56 78 90".
Now we can enter 5 numbers and scanf see where one number begin and where it end.
But there is another problem. It dosn't matter what we enter, scanf is allways happy.
If we enter "12 34 56", scanf assign 12 to x[0], 34 to x[1] and 56 to x[2].
x[3] and x[4] will leave unchanged (they have garbage values since declaration).
For this case we can use the return value of scanf.
scanf returns the number of successfully assigned elements.
In our case, we want 5 numbers, so scanf should return 5.
Is this not the case, the input was not correct.
The result is:
Code:
…
int x[5], ret;
…
do {
ret = scanf(" %d %d %d %d %d", &x[0], &x[1], &x[2], &x[3], &x[4]);
} while (ret != 5);