如何使用sscanf检查fromstring的数字。我尝试了下面的例子,它是有效的,但我想知道如何包含点数形式的数字,如3.6和负号
warning: Supported source version 'RELEASE_6' from annotation processor 'org.appcelerator.kroll.annotations.generator.KrollJSONGenerator' less than -source '1.7'
[ERROR] : Note: [KrollBindingGen] Running Kroll binding generator.
[ERROR] : Note: [KrollBindingGen] No binding data found, creating new data file: org.appcelerator.titanium.bindings/chart.json
[ERROR] : Note: [KrollBindingGen] Found binding for module Chart
[ERROR] : Note: [KrollBindingGen] Found binding for proxy Chart
[ERROR] : Note: [KrollBindingGen] Found binding for proxy Line
[ERROR] : /Users/i706495/Documents/Mobile/AppcWorkspace/chartnew/android/src/ingrs/chart/Crosshair.java:7: error: package com.artfulbits.aiCharts.Base does not exist
[ERROR] : import com.artfulbits.aiCharts.Base.ChartArea;
答案 0 :(得分:2)
如果只是扩展sscanf
- 方法,那么只需添加-+.
- 字符,并使用数据类型float
或double
,它们可以代表浮点数值:
int main() {
char * string = "xx=3300 rr=3.6 zz=-0.8";
float val;
if(sscanf(string, "%*[^-+.0123456789]%f", &val)==1)
printf("%f\n", val);
else
printf("not found\n");
return 0;
}
然而,更好的方法是首先将字符串拆分为标记,例如,基于空格或=
- 符号,这样您就可以准确地知道输入中数字的位置;然后你可以将一个字符串转换为你选择的数字。这种方法可能如下:
int main() {
char string[] = "xx=3300 rr=3.6 zz=-0.8";
char *pair = strtok(string," ");
while (pair) {
char *beginOfVal = strchr(pair, '=');
if (beginOfVal) {
beginOfVal++;
char *endOfVal;
double val = strtod(beginOfVal, &endOfVal);
if (endOfVal==beginOfVal) {
printf("error scanning %s as a number.\n", beginOfVal);
}
else {
printf("val: %lf\n", val);
}
}
pair = strtok(NULL," ");
}
}
答案 1 :(得分:2)
您不应该使用sscanf
,因为您应该never use any of the scanf
functions for anything。
您应该使用strchr
组合来扫描等号,并使用strtod
将文本转换为机器浮点。这是必要循环的草图:
void read_numbers_from_string (const char *str, void (*callback)(double))
{
while (*str)
{
char *p = strchr(str, '=');
if (!p) break;
errno = 0;
char *endp;
double n = strtod(p + 1, &endp);
if (endp > p + 1 && !errno)
callback(n);
str = endp;
}
}
未测试。 strtod
周围的错误处理可能不足以满足您的应用需求 - 请仔细阅读strtod
联机帮助页的NOTES部分。
答案 2 :(得分:1)
strpbrk
可用于查找第一个数字,符号或点。使用strtol
或strtod
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char * string = "xx=3300 rr=3.6 zz=-0.8 .89 4e-5";
char *each = string;
char *start = NULL;
char *stop = NULL;
long int val = 0;
double dbl = 0.0;
while ( ( start = strpbrk ( each, "0123456789.+-"))) {//find digit sign or dot
val = strtol ( start, &stop, 10);//parse a long
if ( '.' == *stop || 'e' == *stop) {//found a dot
dbl = strtod ( start, &stop);//parse a double
printf("%f\n", dbl);
}
else {
printf("%ld\n", val);
}
if ( start == stop) {//unable to parse a long or double
break;
}
each = stop;
}
return 0;
}