getting garbage output for converting start of string to integer

  atoi, c++, char, integer, string

I am supposed to make a function which outputs integers at the start of string.

int num_neg(char a_){
    if(a_ == '0' || a_ == '1' || a_ == '2' || a_ == '3' || a_ == '4' || a_ == '5' || a_ == '6' || a_ == '7' || a_ == '8' || a_ == '9' || a_ == '-') return 1;
    else return 0;
}
int char_num(char b_){
    if(b_ == '0') return 0;
    if(b_ == '1') return 1;
    if(b_ == '2') return 2;
    if(b_ == '3') return 3;
    if(b_ == '4') return 4;
    if(b_ == '5') return 5;
    if(b_ == '6') return 6;
    if(b_ == '7') return 7;
    if(b_ == '8') return 8;
    if(b_ == '9') return 9;
    // else return -1;
}
int Solution::atoi(const string A) {
    int M = A.size();
    int num=0;
    int x;
    int flag = 0;
    int neg = 0;
    for(int i=0; i<M; i++){
        if(A[i] == ' ' && flag == 0) continue;
        if(num_neg(A[i]) == 0){
            break;
        }
        if(A[i] == '-'){
            if(neg == 1) break;
            neg = 1;
            flag = 1;
            continue;
        }
        x = char_num(A[i]);
        num = num*10 + x;
        if(flag == 0) flag = 1;
    }
    if(neg == 1) num = -num;
    if(num > INT_MAX) return INT_MAX;
    if(num < INT_MIN) return INT_MIN;
    return num;
}

Assume int Solution::atoi() is a function called in main function with inputs as string. I am getting garbage output for input of A = "+7" while expected output is "7". What am I doing wrong in here.

EDIT: the input case was wrong in the previous question asked. The problem was with input: "+7" and I got it resolved. Thanks to everyone.

Source: Windows Questions C++

LEAVE A COMMENT