Thursday 9 August 2012

Conver string to int (C++ code)

#include<cstring>

int pow(int n,int i){
    int rez = 1;
    while(i){
        rez*=n;
        i--;
    }
    return rez;
}
bool Check_char(const char *str){
    if(str[0]=='-'){
        for(int i=1;i<strlen(str);i++){
            if((str[i]<'0')||(str[i]>'9')){
                return false;
            }
        }
    return true;
    }
    else {
        for(int i=0;i<strlen(str);i++){
            if((str[i]<'0')||(str[i]>'9')){
                return false;
            }
        }
    return true;
       
    }
}
int Char_to_Int(char *str){

    if(!Check_char(str)){
        printf("Error !!!\nString is not only numbers.\n");
        return -1;
    }

    int l,rez,j=1;
    l=strlen(str)-1;
    rez = str[l]-48;

    for(int i=l-1;i>=(str[0]!='-'?0:1);i--){
        rez+=(str[i]-48)*pow(10,j);
        j++;
    }

    return str[0]!='-'?rez:-rez;
   
}

No comments:

Post a Comment