从c中的stdin中读取多个浮点数的有效方法是什么? (元素数量未知,格式未知))

时间:2014-11-25 04:47:06

标签: c floating-point stdin

我最近遇到了在各种情况下从stdin中读取多个浮点数的需求。到目前为止,我使用的大部分内容都是scanf(),但我想知道是否有一种通用/可靠的方法来处理这个问题。

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:2)

您可以在floats中通过循环调用stdin轻松阅读strtof#include <stdio.h> #include <stdlib.h> int main () { char *line = NULL; /* buffer to hold input on stdin */ char *sp = NULL; /* start pointer for parsing line */ char *ep = NULL; /* end pointer for parsing line */ int cnt = 0; /* simple counter for floats */ float flt = 0.0; /* variable to hold float */ printf ("\n enter any number of floats you like as input ([enter] without number to quit)\n"); while (printf ("\n input: ") && scanf ("%m[^\n]%*c", &line) >= 1) { cnt = 0; sp = line; while (*sp) { flt = strtof (sp, &ep); /* convert value to float */ if (sp != ep) { /* test that strtof processed chars */ sp = ep; /* set sp to ep for next value */ printf (" float [%d] %f\n", cnt+1, flt); /* output the float value read */ cnt++; /* increase float count */ } else { break; } sp++; /* skip space or comma separator */ } } if (line) free (line); /* free memory allocated by scanf */ return 0; } 。一种方法如下:

$ ./bin/floatread

 enter any number of floats you like as input ([enter] without number to quit)

 input: 2.3 4.5 6.7, 8.1
  float [1]  2.300000
  float [2]  4.500000
  float [3]  6.700000
  float [4]  8.100000

 input: 21.3.45.6,81.2,99.3 29.8
  float [1]  21.299999
  float [2]  45.599998
  float [3]  81.199997
  float [4]  99.300003
  float [5]  29.799999

 input:

<强>输入/输出:

{{1}}