我如何从字符串返回float [英] How will I return float from a string

查看:96
本文介绍了我如何从字符串返回float的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我有一个字符串为ex:



输入:你好,23.78世界64.7string



输出:

23.78

64.7



在此字符串中如何从此字符串返回浮点数请帮助我们用这个代码进行编码



我尝试过:



Suppose I am having a string for ex:

Input: hello, 23.78 world 64.7string

Output:
23.78
64.7

In this string how will I return float numbers from this string please help to code this in c

What I have tried:

#include<stdio.h>
main()
{
  char c[100];
  char *pc;
  pc = c;
  float i;
  
  gets(c); //getting the string input
  
  while(pc != '\0')
  {
    if(isdigit(*pc)
    {
       i = i * 10 + (*pc - '0');
    }
    pc++;
  }
  printf("%f",i);
}

推荐答案

分两个阶段完成:

1)查找一个连续的系列或更多数字,可选的单个小数点。保持指向第一个数字/小数点的指针,并用空值覆盖第一个不匹配的字符。

2)您现在可以使用 atof - C ++参考 [ ^ ]使用您在阶段1中保存的指针转换值。
Do it in two stages:
1) Find a contiguous series of one or more digits, with an optional single decimal point. Keep a pointer to the first digit / decimal point, and overwrite the first non-matching character with a null.
2) You can now use atof - C++ Reference[^] to convert the value using the pointer you saved in stage 1.


这篇关于我如何从字符串返回float的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆