代码之家  ›  专栏  ›  技术社区  ›  Huan

试图编写函数,试图从字符串中提取数字,但返回的是不相关的数字[已关闭]

  •  -1
  • Huan  · 技术社区  · 8 年前

    我试图编写一个函数,从存储在char数组中的字符串中提取数字。E、 g.输入:“141923adsfab321221.222”,我的函数应该返回141923和321221.222。下面是我到目前为止得出的结果,它运行并编译,但不管我如何更改输入,它都会输出完全不相关的数字,如48 49 50 51等。请帮忙。

    #include <iostream>
    #include <bits/stdc++.h>
    using namespace std;
    double GetDoubleFromString(char * str){
        static char * start;
        //starting point of the search
        if(str)
            start=str;
        //check if str is empty
        for (;*start&&!strchr("0123456789.",*start);++start);
        //jump thru chars that are not num related
        if (*start=='\0'){
            return -1;
        // check if at the end of the string
        }
        char *q=start;
        //mark the position of the start of a number
        for (;*start&&strchr("0123456789.",*start);++start);
        //jump thru chars that are num related
        if (*start){
            *start='\0';
            ++start;
        //as *start rest at a non num related char, mutate it to \0 and push forward
        }
        return *q;
        //I tried return (double) *q; but that does not work either and in the same way
    }
    
    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 回复  |  直到 8 年前
        1
  •  1
  •   kmdreko    8 年前

    看起来您的数字分隔代码是正确的,但您缺少转换字符数组的关键步骤 ['1', '4', '1', '9', '2', '3', '\0'] 变成双人 141923 .标准库具有 std::atof 专门为此目的而设计。

    您只需在返回时使用它,如下所示:

    return std::atof(q);