从 C 中的字符串开头拆分浮点数
Split float from beginning of string in C
我目前正在用 C 编写一个程序,它可以标记一个算术表达式,但我在这里只提供了一个最小的、可重现的示例。
以下代码成功地将 -5.2foo
拆分为 -5.2
和 foo
:
#include <stdio.h>
int main(void)
{
char str[] = "-5.2foo";
float f;
sscanf(str, "%f%s", &f, str);
printf("%f | %s\n", f, str);
return 0;
}
但是如果字符串只包含一个浮点数(例如-5.2
),程序会打印-5.2 | -5.2
,所以字符串看起来并不为空。有没有办法在 C 中从字符串中拆分出一个浮点数,然后存储剩余的字符串?
您可以使用 strtof()
function,它有一个参数(可选)return 指向输入字符串的 'rest' 的指针(在 float
具有已提取):
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[] = "-5.2foo";
char* rest;
float f;
f = strtof(str, &rest);
printf("%f | %s\n", f, rest);
// And, if there's nothing left, then nothing will be printed ...
char str2[] = "-5.2";
f = strtof(str2, &rest);
printf("%f | %s\n", f, rest);
return 0;
}
来自上面链接的 cppreference 页面(str_end
是第二个参数):
The functions sets the pointer pointed to by str_end to point to the
character past the last character interpreted. If str_end is a null
pointer, it is ignored.
如果输入字符串中没有 'left',则 returned 值将指向该字符串的终止 nul
字符。
我目前正在用 C 编写一个程序,它可以标记一个算术表达式,但我在这里只提供了一个最小的、可重现的示例。
以下代码成功地将 -5.2foo
拆分为 -5.2
和 foo
:
#include <stdio.h>
int main(void)
{
char str[] = "-5.2foo";
float f;
sscanf(str, "%f%s", &f, str);
printf("%f | %s\n", f, str);
return 0;
}
但是如果字符串只包含一个浮点数(例如-5.2
),程序会打印-5.2 | -5.2
,所以字符串看起来并不为空。有没有办法在 C 中从字符串中拆分出一个浮点数,然后存储剩余的字符串?
您可以使用 strtof()
function,它有一个参数(可选)return 指向输入字符串的 'rest' 的指针(在 float
具有已提取):
#include <stdio.h>
#include <stdlib.h>
int main(void)
{
char str[] = "-5.2foo";
char* rest;
float f;
f = strtof(str, &rest);
printf("%f | %s\n", f, rest);
// And, if there's nothing left, then nothing will be printed ...
char str2[] = "-5.2";
f = strtof(str2, &rest);
printf("%f | %s\n", f, rest);
return 0;
}
来自上面链接的 cppreference 页面(str_end
是第二个参数):
The functions sets the pointer pointed to by str_end to point to the character past the last character interpreted. If str_end is a null pointer, it is ignored.
如果输入字符串中没有 'left',则 returned 值将指向该字符串的终止 nul
字符。