字符串转化为数字 aotf



#include
using namespace std;




float str2num(char *p){
    float tmp = 0.0;
    int dot = 0;
    float n = 1.0;
    const char *str = p;
    if (*str == '-' || *str == '+'){
        str++;
    }
    while(*str != 0){
        if(dot == 0){
            if(*str <= '9' && *str >= '0'){
                tmp = tmp*10 + ((*str) - '0');
            } else if (*str == '.') {
                dot = 1;
            } else {
                break;
            }
        } else {
            if(*str <= '9' && *str >= '0'){
                n = n*10;
                tmp +=  ((*str) - '0')/n;
            } else {
                break;
            }
        }
        str++;
    }
    if (*p == '-'){
        tmp = -tmp;
    }
    return tmp;
}




int main(){
    float n=0.0;
    char p[50]="";
    cin.getline(p,20);
    n = str2num(p);
    cout <<  n << endl;
}

你可能感兴趣的:(字符串转化为数字 aotf)