计数传递给C中的scanf()的参数

时间:2015-02-18 15:19:07

标签: c arrays count arguments scanf

有没有办法计算在C中传递给scanf()的参数数量?特别是,通过int分配scanf()数组时。 例如:

int array[1000], i;
for(i=0;i<1000;i++)
    scanf("%d",&array[i]);

我需要计算用户插入了多少个值

2 个答案:

答案 0 :(得分:2)

我认为没有内置的方法可以做到这一点,但为什么不创建一个在scanf成功返回时递增的计数器,否则会打破循环?

int scanf_counter = 0;
int array[1000], i;

for(i=0;i<1000;i++) {

    if(scanf("%d",&array[i] > 0) {
        scanf_counter++;
    } else {
        break;
    }

}

虽然我不确定我完全理解你的问题,因为你总能通过这样做找到数组的大小

int size = sizeof(array)/sizeof(array[0])

答案 1 :(得分:0)

仔细查看scanf()片段,因此:

包括

int main()

{     double a [100000],mx = 0;

int i,j,c=0;
printf("Enter as many numbers as you wish . Press Ctrl+D or any character to stop inputting :\n");  

for(i=0;i<100000;i++)

{
    if((scanf("%lf",&a[i]))==1)

        c++;

    //else break;

}

for(j=0;j<c;j++)

{
    if(a[j]>mx) mx=a[j];
}

printf("You have inserted %d values and the maximum is:%g",c,mx);


return 0;

}