【发布时间】:2021-12-12 06:17:05
【问题描述】:
我正在尝试读取一行浮点值,例如
1.1 -100.0 2.3
我需要将它们存储在一个数组中。
我正在使用fgets() 方法将输入转换为字符串。无论如何我可以使用这个字符串来填充一个浮点数组的值吗?或者有更好的方法吗?
#include <stdio.h>
int main(){
char input [500];
float values [50];
fgets(input, 500, stdin);
// now input has a string with all the values
// and the values array needs to be filled with the values
}
【问题讨论】:
-
使用
strtok()分割输入字符串,然后调用atof()将每一个转换为float。 -
如果它始终是固定/已知的浮点数,那么也可以使用
sscanf。 -
修改@kaylum 的建议:
sscanf
标签: c floating-point extract c-strings fgets