C scanf - 未知数组大小

标签 c scanf

我想将值( float )读入数组,但我不知道值的数量。

我的输入是这样的

Enter values: 1.24 4.25 1.87 3.45 .... etc

如何将此输入加载到数组?我知道输入 0 或 EOF 时输入结束。

while(0 or EOF){
   scanf("%f", &variable[i])
   i++;
}

谢谢。

最佳答案

您可以动态分配数组,然后在先前分配的缓冲区已满时为其重新分配内存。请注意,scanf 格式字符串中的转换说明符 %f 读取并丢弃前导空白字符。来自 scanf 的手册页 -

scanf returns the number of items successfully matched and assigned which can be fewer than provided for, or even zero in the event of an early matching failure. The value EOF is returned if the end of input is reached before either the first successful conversion or a matching failure occurs.

这意味着 scanf 只有在遇到 EOF 作为调用时的第一个输入时才会返回 EOF 因为 EOF 必须以换行符 '\n' 开头,否则它将不起作用(取决于操作系统)。这里有一个小程序来演示如何做到这一点。

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

int main(void) {
    size_t len = 4;
    float *buf = malloc(len * sizeof *buf);

    if(buf == NULL) {     // check for NULL        
        printf("Not enough memory to allocate.\n");
        return 1;
    }

    size_t i = 0;
    float *temp; // to save buf in case realloc fails

    // read until EOF or matching failure occurs
    // signal the end of input(EOF) by pressing Ctrl+D on *nix
    // and Ctrl+Z on Windows systems

    while(scanf("%f", buf+i) == 1) { 
        i++;
        if(i == len) {               // buf is full
            temp = buf;
            len *= 2;
            buf = realloc(buf, len * sizeof *buf);  // reallocate buf
            if(buf == NULL) {
                printf("Not enough memory to reallocate.\n");
                buf = temp;
                break;
            }
        }
    }

    if(i == 0) {
        printf("No input read\n");
        return 1;
    }

    // process buf

    for(size_t j = 0; j < i; j++) {
        printf("%.2f ", buf[j]);
        // do stuff with buff[j]
    }

    free(buf);
    buf = NULL;

    return 0;
}

关于C scanf - 未知数组大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22165565/

相关文章:

c++ - double 的有效小数位数?

c++ - 如何在 C 和 C++ 中设计具有并行接口(interface)的库

c - 在没有 float 的情况下处理 C 中的小数

c - fscanf 读取输入文件的问题

c - Visual Studio 2015 上的 scanf

c - 静态内联 vs 内联静态

c - 使用动态内存分配返回指向结构的指针

使用 sscanf 控制整个字符串

使用具有固定大小类型的 scanf/printf(和系列)的正确方法?

c - fscanf 没有正确读取 double