【问题标题】:How to read in multiple floats on one line and then add them to an array?如何在一行上读取多个浮点数,然后将它们添加到数组中?
【发布时间】: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
  • 教程见these class notes

标签: c floating-point extract c-strings fgets


【解决方案1】:

您可以为输入的字符串应用sscanf

这是一个简化的演示程序。

#include <stdio.h>

int main(void) 
{
    char input[20];
    float values[3];
    
    fgets( input, sizeof( input ), stdin );
    
    size_t n = 0;
    char *p = input;
    
    for ( int pos = 0; n < 3 && sscanf( p, "%f%n", values + n, &pos ) == 1; p += pos )
    {
        ++n;
    }
    
    for ( size_t i = 0; i < n; i++ )
    {
        printf( "%.1f ", values[i] );
    }
    
    putchar( '\n' );
    
    return 0;
}

如果输入的字符串是

1.1 -100.0 2.3

那么数组values的输出就是

1.1 -100.0 2.3

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2016-08-18
    • 2020-08-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    相关资源
    最近更新 更多