我正在编写一个函数,从存储在字符数组中的字符串中提取数字。 例如输入:"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==' '){
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=' ';
++start;
//as *start rest at a non num related char, mutate it to 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', '4', '1', '9', '2', '3', ' ']
转换为双141923
的关键步骤。标准库具有专门为此目的而设计的功能std::atof
。
您只需在返回时使用它,如下所示:
return std::atof(q);