Reputation: 339
How may I count & extract a number of elements from stdin?
For instance, len() is easily available in Python, but not in C?
Im trying to compute an average, when user enters for eg: 1 3 5 7 8 10 11 -1
I've tried the following:
while (user_input != -1)
{
total += user_input;
scanf ("%d", &user_input);
//cannot work
average = total / ...
}
printf("Average = %f\n", average);
Upvotes: 2
Views: 3995
Reputation: 25705
You'll have to maintain a counter to do what you're trying to do. its just int counter = 0;
and in the loop: counter++
int counter = 0;
while (user_input != -1)
{
total += user_input;
counter ++;
scanf ("%d", &user_input);
}
average = total / counter;
printf("Average = %f\n", average);
obviously, you'll have to check if scanf()
returned atleast 1
--- EDIT ---
the following program(that corresponds to the previous program) is VALID and works as required. People who do not understand how scanf()
works, should stay the damn out:
#include <stdio.h>
int main(int argc, char *argv[])
{
int total = 0;
float average = 0.0f;
int userinput = 0;
int counter = -1;
while(userinput != -1){
counter ++;
if(scanf("%d",&userinput) == 1 && userinput != -1){
total += userinput;
}
}
average = ((float)total/(float)counter);
printf("Average = %f", average);
return 0;
}
Input: 10 20 30 40 50 60 -1
Output: Average = 35
Upvotes: 1
Reputation: 206518
From your modified question & comments, it seems what you really want to do is read a line of input from the user and then extract numbers from that line of input.
The answer is you cannot do that using scanf
, You need to use fgets
to read the line from stdin
and then you need to extract numbers from that read line. Here is a,
Quick sample program:
#include<stdio.h>
int main()
{
char line[1024], *beg, *end;
long readvalue;
while (fgets(line, sizeof(line), stdin))
{
beg = line;
for (beg = line; ; beg = end)
{
readvalue = strtol(beg, &end, 10);
if (beg == end)
break;
printf("[%d]",readvalue);
}
}
return 0;
}
Input:
1 3 5 7 8 10 11 -1
Output:
[1][3][5][7][8][10][11][-1]
Upvotes: 0