【发布时间】:2018-04-19 05:25:43
【问题描述】:
我正在尝试编写一个从存储在 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;
}
【问题讨论】:
-
你的函数返回数字的 ASCII 码。你错过了适当的数字算术。
-
@S.M.这就解释了 48 49 50 51........
标签: c++ pointers debugging text-extraction