Originally Posted by
erdemtuna
Because in this code, I want my inputs to be counted and output it as how many variable I entered.
How can I use scanf to count the quantity of entered variables?
As I said before, the input is correctly counted - the output is just not what you expect. Each digit is its own character, as I explained before. I hope that is clear. scanf can be used to improve the output, so it is more like you expect.
Normally scanf will analyze the input and try to match it with the conversions specified in the first argument. When there is a match, the value is stored in the corresponding pointer to a variable. Once that is understood, then the next thing is to control the loop using the return value of the function.
So, as an example, let's recreate the broken getchar version using scanf and try to understand its meaning. This may help us realize where we went wrong.
Code:
while (scanf("%c", &c) == 1) {
b += 1;
}
This will take every character and store it in c. The characters are counted in b.
So if the user enters:
10
20
30
^Z
The result is 9, because of each digit and the three newline characters.
The return value of scanf is different too, as you've no doubt realized. If we turn to the manual page though, there is a clear explanation for that.
[scanf] return the number of input items successfully matched and assigned, which can be fewer than provided for, or even zero in the event of an early matching failure.
The value
EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs.
By my reading of this, since we have one thing we want to match, the easiest way to stop the loop is at the point scanf() does not return 1.
But the output is not what you expect. Luckily, scanf can analyze the input in more ways than getchar can. The easiest, and most permissive way to change scanf is to look for integers, instead:
Code:
while (scanf("%i", &c) == 1) {
b += 1;
}
So now this counts integers - the input:
10
20
30
^Z
would make 3.