C++怎么从一行字符串中提取想要的数字,如m=45.5,D=0.15494,l=0.89989,A=1.803,C=0.161,提前45.5等数字

谢谢

C++有很多从字符串中提取数值的办法,不同类型的程序、不同的开发环境都有不少办法。

比较通用(但格式比较严格)的,是sscanf函数,从一个字符串中格式化提取整数、浮点数都没有问题。

比如:

char s[] = "m=45.5,D=0.15494";
double m,d;
sscanf(%*[^=]=%f,D=%f",&m,&d);

追问

非常感谢,我试试看

追答

不客气。
如果格式非常严格,直接:
m=%f,D=%f
这样就可以了,不需要正则匹配。

追问

应该是%lf,谢谢了。

温馨提示:答案为网友推荐,仅供参考
第1个回答  2015-03-17

把cout改成你想要的操作:

void print_integers(const char* str)
{
  char buf[255];
  int count = 0;
  for (int i = 0; ; i ++)
    {
      char c = str[i];
      if ((c <= '9' && c >= '0') || c == '.')
  buf[count++] = c;
      else
{
  buf[count] = '\0';
  count = 0;
  double num = atof(buf);
  cout << num << endl;
}
      if (c == '\0')
break;
    }
}

第2个回答  2015-03-17
float getNumberFromString(char * ch)
{
float t;
char * pc;
char * res = 0;
int count = 0;
int dotNum = 0;
int minusNum = 0;
for(pc = ch; *pc!=0; pc++)
{
if(*pc==46 || *pc==45 || (*pc>47&&*pc<57)
{
res = (char*)realloc(res,(count+1)*sizeof(char));
if(!res)
{
printf("out of memory!\n");
return 0.f;
}
res[count] = *pc;
if(*pc == 45)
{
if(count!=0 || minusNum!=0)
{
printf("erro string format!\n");
if(res)
free(res);
return 0.f;
}
else
minusNum += 1;
}
if(*pc==46)
{
if(dotNum!=0)
{
printf("erro string format!\n");
if(res)
free(res);
return 0.f;
}
else
dotNum += 1;
}
count +=1;
}
}
res = (char*)realloc(res,(count+1)*sizeof(char));
if(!res)
{
printf("out of memory!\n");
return 0.f;
}
res[count] = 0;
t = atof(res);
if(res)
free(res);
return t;
}
是我想复杂了???呵呵

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网