在按下ENTER键之前读取C中的整数

在按下ENTER键之前读取C中的整数,c,arrays,scanf,enter,C,Arrays,Scanf,Enter,我想读取数组中可变数量的整数,直到用户按Enter键。我通过以下方式实现了这一目标: printf("Give the numbers in the array, then hit ENTER: \n"); scanf("%d", &array[i]); i++; no_elements++; while (scanf(line, "%d", &array[i++])== 1) { scanf("%d", &array[i]); i++; no_

我想读取数组中可变数量的整数,直到用户按Enter键。我通过以下方式实现了这一目标:

printf("Give the numbers in the array, then hit ENTER: \n");
scanf("%d", &array[i]);
i++;
no_elements++;

while (scanf(line, "%d", &array[i++])== 1) {
    scanf("%d", &array[i]);
    i++;
    no_elements++;
}
另一方面,我在一个网站上发现了这一点,我不完全理解scanf测试。它的工作原理是当我按下回车键时,读数停止。但是,不管怎样,读取的整数数最终都等于一(通过添加printf指令检查)。为什么呢?我还能怎么做呢

注:变量i在开始时设置为0,因为没有_元素;行被声明为char行[20]

#包括
#include <stdio.h>

int main() {
    int i=0, no_elements = 0;
    int array[16];

    while(no_elements<16){
        char line[32];
        int n;
        printf("Give the numbers in the array, then hit ENTER: \n");
        fgets(line, sizeof(line), stdin);
        if(*line == '\n')
            break;
        if(1==sscanf(line, "%d", &n))
            array[no_elements++]=n;
    }
    printf("%d\n", no_elements);
    return 0;
}
int main(){ int i=0,无元素=0; int数组[16]; 而在C中(无元素 如果输入是用空格分隔的整数,在最终输入之后,如果按enter键,我们可以读取如下内容:

#include <stdio.h>
#include <stdlib.h>

int main()
{
    int ar[10],i=0;
    char c=' ';
    while(c!='\n'){
        scanf("%d%c",&ar[i++],&c);
    }
    while(i>0)
        printf("%d\t",ar[--i]);
 }
#包括
#包括
int main()
{
int-ar[10],i=0;
字符c='';
而(c!='\n'){
scanf(“%d%c”、&ar[i++]、&c);
}
而(i>0)
printf(“%d\t”,ar[--i]);
}
#包括
void main()
{int a[100],i,sum=0,count=0;
字符c;
对于(i=0;c!='\n';i++)
{scanf(“%d%c”、&a[i]、&c);
计数++;
}

对于(i=0;该代码有很多问题,例如,在循环中读取输入两次。我想我可以使用第一次扫描作为条件,检查用户是否只添加了整数(?)这样做的一个好选择是什么?只使用该
scanf
进行读取和检查。跳过循环外部的第一个调用,以及循环体内部的第一个调用。谢谢。不过,我有点像个noob。现在循环之后,没有元素的整数数是0。我不确定它是否甚至进入while循环。你可以跳过它,或者你可以它初始化它c=“”欢迎使用Stack Overflow!感谢您提供此代码片段,它可能会提供一些有限的短期帮助。请通过说明为什么这是一个很好的问题解决方案来正确解释它的长期价值,并使它对将来有其他类似问题的读者更有用。请您的答案添加一些解释,包括你已经做过的总结。可能也值得将代码格式化为更传统的布局。
#include<stdio.h>
void main()
{int a[100],i,sum=0,count=0;
char c;
for(i=0;c!='\n';i++)
{scanf("%d%c",&a[i],&c);
 count++;
}
for(i=0;i<count;i++)
    {sum=sum+a[i];}
printf("%d",sum);
getch();}`