有没有办法使用sscanf()
来计算字符串中的浮点数?
count = sscanf(string, " %f %f /* an so on.. */", &temp, %temp2 /* ..*/);
我可以放置大量"%f"
和变量,但似乎是愚蠢的想法,有什么方法可以使它灵活吗?
你能帮帮我吗?
编辑:我试图以这种方式使用strtok()
,但它不起作用
substring = strtok(lines_content, " " );
temp = sscanf(substring, "%f", &value);
if(temp == 1)
{
no_of_floats_in_line++;
}
fflush(stdin);
while(token = strtok(NULL, " ") != NULL)
{
substring = strtok(NULL, " ");
temp = sscanf(substring, "%f", &value);
fflush(stdin);
if(temp == 1)
{
no_of_floats_in_line++;
}
}
答案 0 :(得分:1)
这是一个使用strtok()
隔离字符串中每个浮点数的解决方案。
#include <stdio.h>
#include <string.h>
int main (void) {
char flotsam[] = "0.0 1.1 2.2 PI 4.4";
char *tok;
float jetsam;
int count = 0;
tok = strtok(flotsam, " \f\r\n\t\v");
while (tok) {
if (sscanf(tok, "%f", &jetsam) == 1) {
count++;
printf ("Float is %f\n", jetsam);
}
else
printf ("Error with %s\n", tok);
tok = strtok(NULL, " \f\r\n\t\v");
}
printf ("Found %d floats\n", count);
return 0;
}
节目输出:
Float is 0.000000
Float is 1.100000
Float is 2.200000
Error with PI
Float is 4.400000
Found 4 floats