尝试编写函数尝试从字符串中提取数字,但它返回不相关的数字
Trying to write function trying to extract number from a string, but it is returning unrelated number
我正在尝试编写一个函数,从存储在 char 数组中的字符串中提取数字。例如。输入:“141923adsfab321221.222”,我的函数应该 return 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=='[=10=]'){
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='[=10=]';
++start;
//as *start rest at a non num related char, mutate it to [=10=] 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', '[=11=]']
转换为双精度数组 141923
的关键步骤。标准库具有专门为此目的设计的函数 std::atof
。
您只需在 return 处使用它,就像这样:
return std::atof(q);
我正在尝试编写一个函数,从存储在 char 数组中的字符串中提取数字。例如。输入:“141923adsfab321221.222”,我的函数应该 return 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=='[=10=]'){
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='[=10=]';
++start;
//as *start rest at a non num related char, mutate it to [=10=] 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', '[=11=]']
转换为双精度数组 141923
的关键步骤。标准库具有专门为此目的设计的函数 std::atof
。
您只需在 return 处使用它,就像这样:
return std::atof(q);