简体   繁体   中英

Printing an integer value from an ASCII character

I am trying to implement the function stoi() in c++. I have made an int array arr to store the integer ASCII of all elements of char_arr . This works fine if I print the values from my char_arr array because its a character array. But, how do I transfer my integer values from the char array to an int array and print only the numbers and not their ASCII?

Code:

int stoi(){
        int *arr = new int [strlen(char_arr)];
        for (int i=0; char_arr[i]!='\0'; ++i){
            arr[i] = char_arr[i];
        }
        for (int i=0; char_arr[i] != '\0'; ++i){
            if (arr[i] >= 48 && arr[i] <= 57){
                cout << char_arr[i];
            }
        }

    }

First of all, remove the first loop and use char_arr directly. You don't need to hold int s to make it work.

As for printing int values, you can use this:

for (int i = 0; char_arr[i] != '\0'; ++i) {
  if (char_arr[i] >= '0' && char_arr[i] <= '9') { //I would suggest you to use this syntax instead of raw ASCII codes.
    cout << (char_arr[i] - '0');
  }
}
int stoi(){
    /* if you do not use arr.
    int *arr = new int[strlen(char_arr)];
    for (int i = 0; char_arr[i] != '\0'; ++i){
        arr[i] = char_arr[i];
    }
    */
    int sign = 1, value = 0;
    if (*char_arr == '+') {
        ++char_arr;
    }
    else if (*char_arr == '-') {
        ++char_arr;
        sign = -1;
    }
    while (*char_arr) {
        if (*char_arr >= '0' && *char_arr <= '9') {
            value = value * 10 + *char_arr - '0';
            ++char_arr;
        } else {
            break;
        }
    }
    return sign * value;
}

Here's the one I came up with:

#include <cstdio>
#include <cstring>

#define _BASE_  10

int main(int argc, char **argv)
{
    char ascii[] = "474927";
    signed int value = 0;

    signed int ascii_len = strlen(ascii);

    int pos = 0;
    for(signed int i = ascii_len-1; i >= 0; i--)
    {
        if(i == 0 && ascii[i] == '-')
        {
            value *= -1;
            continue;
        }

        int base = 1;

        if(pos > 0)
        {
            base = _BASE_;

            for(int j = 1; j < pos; j++)
                base *= _BASE_;
        }

        value += base * (ascii[i] - 48);
        pos++;
    }

    printf("Value: %d\n", value);

    return 0;
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM