我正在嘗試讀取一行浮點值,例如
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
}
uj5u.com熱心網友回復:
您可以申請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
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/338879.html
下一篇:C中的無限正弦生成
