我想将值(浮点数)读入数组,但我不知道值的数量。
我的输入是这个
Enter values: 1.24 4.25 1.87 3.45 .... etc
Run Code Online (Sandbox Code Playgroud)
如何将此输入加载到数组?我知道输入 0 或 EOF 时输入结束。
while(0 or EOF){
scanf("%f", &variable[i])
i++;
}
Run Code Online (Sandbox Code Playgroud)
谢谢你。
您可以动态分配数组,然后在先前分配的缓冲区已满时为其重新分配内存。请注意,%f格式字符串中的转换说明符scanf读取并丢弃前导空白字符。从手册页scanf-
scanf返回成功匹配和分配的项目数量,该数量可能少于提供的数量,或者在早期匹配失败的情况下甚至为零。如果在第一次成功转换或匹配失败发生之前到达输入末尾,则返回值 EOF。
这意味着只有在它被调用时作为第一个输入遇到时scanf才会返回,因为必须以换行符开头,否则它将不起作用(取决于操作系统)。这是一个小程序来演示如何做到这一点。EOFEOFEOF'\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;
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19150 次 |
| 最近记录: |