我想写一个从存储在char数组中的字符串中提取数字的函数。例如。输入:“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;
}
答案 0 :(得分:1)
看起来您的数字分隔代码是正确的,但您错过了将字符数组['1', '4', '1', '9', '2', '3', '\0']
转换为双141923
的关键步骤。标准库具有专门为此目的而设计的函数std::atof
。
你只需在返回时使用它:
return std::atof(q);