从字符串中取数

编写GetDoubleFromString函数,该函数可以不断从字符串中取出正浮点数或整数,无数可取,则返回值小于0
输入
多组数据,每组数据一行
输出
针对每组数据,将其中的数输出来。每行一个数,保留小数点后面6位。输入数据中只会有正数,不用考虑负号。两个数之间有至少一个非数字非小数点的字符。
样例输入

please 121a1 stand 0.7 9.2 1010.3983 0.00001 black stand what 1324.3
12.34 45 78ab78.34

样例输出

121.000000
1.000000
0.700000
9.200000
1010.398300
0.000010
1324.300000
12.340000
45.000000
78.000000
78.340000

没有很复杂,仔细想一想就能写出来。其实就是strtok的改编

#include <iostream>
#include <iomanip>
using namespace std;
double GetDoubleFromString(char * str)
{
// 在此处补充你的代码
    static char * start;
    double ans = 0;
    if(str)
        start = str;
    for(; *start&&(*start<'0' || *start >'9'); ++start);

    if(*start == 0)
        return -1;
    for(; *start&&(*start>='0' && *start <='9'); ++start)
    {
        ans = ans*10.0 + (*start-'0');
    }
    if(*start=='.')
    {
        start++;
        double k = 10.0;
        for(; *start&&(*start>='0' && *start <='9'); ++start)
        {
            ans = ans + (*start-'0')/k;
            k *= 10;
        }
    }
    return ans;
}

int main()
{
    char line[300];
    while(cin.getline(line,280))
    {
        double n;
        n = GetDoubleFromString(line);
        while( n > 0)
        {
            cout << fixed << setprecision(6) << n << endl;
            n = GetDoubleFromString(NULL);
        }
    }
    return 0;
}

一步一步往上爬。

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值