我需要使用 scanf
函数读取用户输入的未知数量的各种数字。这仅仅意味着各种整数的数量由用户通过发送尽可能多的数字来确定。请注意,我直接读取了数字(我必须这样做),如以下代码所述:
int main(void)
{
int numbers[];
int error = 0;
int i = 0;
while(scanf("%i", &numbers[i++]) == 1);
for(int i = 0; i < sizeof(numbers) - 1; ++i) {
if(numbers[i] < -10000 || numbers[i] > 10000)
{
printf("%i%s", numbers[i], ", ");
}
else
{
printf("%s", "\b\b\nError: Error: Vstup je mimo interval!\n");
// Means "Input is out of range!".
// We have to write exact output to terminal as stated in HW.
i = sizeof(numbers);
error = 1;
}
}
...
}
int error
其实是一个boolean值,不过我懒得实现boolean库,所以定义成整数:D
但是,问题出在别处。编译器向我抛出一个错误:
main.c:7:9: error: array size missing in ‘numbers’
int numbers[];
^
看起来 C 程序需要知道数组的可分配大小。我已经查看了其他人在那里共享的一些代码,以找出我需要实现的基础知识,并且在搜索数组大小问题时,我发现了这个问题:
C - Declaring an array with an undefined value
但是对于直接输入未知数量的数字,并没有解决数组大小未知的问题。我找不到我需要解决的地方。我试图定义数组的最大大小以容纳最多 999 个数字,但随后编译器向我抛出此异常:
main.c:50:23: error: iteration 999u invokes undefined behavior [-Werror=aggressive-loop-optimizations]
if(numbers[j] > 0)
^
main.c:48:9: note: containing loop
for(int j = 0; j < sizeof(numbers); ++j)
^
用于数字统计的每个循环都相同(总数、最大值、最小值、赔率、偶数、正数、负数、它们的百分比和平均值)。这意味着该数组的大小严格为 999 个数字,其余数字为零。我找到了一个 malloc
函数,但不明白它的用法:(
最佳答案
“我需要使用 scanf 函数读取用户输入的各种数字的未知数量。”是一个糟糕的设计目标。
任何允许外部接口(interface)无限制地输入任何量输入的程序都是黑客攻击。
健壮的代码将用户输入限制在大量但合理的输入量内。好的代码会将上限编码为常量或宏。
使用 scanf()
并不是读取用户输入的最佳工具。
推荐 fgets()
读取 行。 (此处未显示。)
#include <stdio.h>
#include <ctype.h>
// find the next character without consuming it.
int peek_ch(void) {
unsigned char ch;
if (scanf("%c", &ch) == 1) {
ungetc(ch, stdin);
return ch;
}
return EOF;
}
#define INPUT_N 1000
void foo(void) {
int input[INPUT_N];
size_t n = 0;
// Read 1 _line_ of input using `scanf("%d", ....)` to read one `int` at a time
for (n = 0; n < INPUT_N; n++) {
int ch;
while (((ch = peek_ch()) != '\n') && isspace(ch))
;
// %d consume leading white-space including \n, hence the above code to find it.
if (scanf("%d", &input[n]) != 1) {
break;
}
}
// TBD: Add code to handle case when n == N
for (size_t i = 0; i < n; i++) {
printf("%zu: %d\n", i, input[i]);
}
}
关于c - 麻烦 : C Declaration of integer array of unknown size,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40193126/