gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 15:37:46 25 4
gpt4 key购买 nike

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

注意:变量i一开始就设置为0,no_elements也是如此; line 被声明为 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;
}

关于c - 读取 C 中的整数,直到按下 ENTER 键,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22079499/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com