使用 sscanf 从 char 字符串中读取固定宽度的浮点数

Reading a fixed width float from char string with sscanf

是否可以使用 sscanf 将下例中的字符串 s 读取为两个 10 个字符(包括空白 space)宽的浮点数?或者我是否必须将 10 个字符的块复制到临时字符数组并在该临时数组上使用 sscanf

#include <stdio.h>
int main( int argc, const char* argv[] )
{
   char s[]={"     6.4887.0522e+06"};
   float f1, f2;

   sscanf(s, "%10f%10f", &f1, &f2);
   printf("%10f %10f\n", f1, f2);
}

我在这个例子中的愿望是从 sscanf 读取中得到 f1 = 6.448f2 = 7052200.

扫描集可能有效。将有效字符放在方括号中。 10 将扫描限制为 10 个字符。 %n 说明符将报告扫描处理的字符数。可以在 sscanf 中使用它来遍历长字符串。

char substr[11] = {'[=10=]'};
char s[]={"     6.4887.0522e+06"};
int offset = 0;
int used = 0;

while ( ( sscanf ( s + offset, "%10[-+.eE 0-9]%n", substr, &used)) == 1) {
    if ( used == 10) {
        printf ( "%s\n", substr);
        //convert as needed
        offset += used;
    }
    else {
        //do something to handle the problem
        break;//one option...
    }
}

如果s[]不是const,暂时使s[10] = 0.

void foo(char *s) {
  while (*s) {
    size_t length = strlen(s);
    char temp = 0;
    if (length > 10) {
      length = 10;
      temp = s[10];
      s[10] = 0;
    } 
    float f1;
    if (sscanf(s, "%f", &f1) == 1) printf("%f\n", f1);
    s += length;
    s[0] = temp;
  }
}