繁体   English   中英

读取C中的整数,直到按ENTER键

[英]Reading integers in C until the ENTER key is pressed

我想读取数组中可变数量的整数,直到用户按下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测试。 它的工作原理是,当我按Enter键时,读数停止。 但是,无论如何,读取的整数数最终都等于1(通过添加printf指令进行检查)。 这是为什么? 我还能怎么做?

注意:变量i在开始时被设置为0,no_elements也被设置为0; 行被声明为char line [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;
}
#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();}`

在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]);
 }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM