Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert only digits to int in a std::string

Tags:

c++

string

int

std

I'm trying to convert only the digits from a string to an int vector, but that gives me the ASCII codes for numbers 0 to 9 instead.

Is there any way to convert only the digits to integers? I guess I'll have to use a char array since atoi() don't work with std::string and the c_str() method don't work for every character, only the entire string.

#include <cctype>
#include <iostream>
#include <vector>

using namespace std;

int main() {
    string chars_and_numbers = "123a456b789c0";
    vector<int> only_numbers;

    for (int i = 0; i < chars_and_numbers.length(); i++) {
        if (isdigit(chars_and_numbers[i])) {
            cout << chars_and_numbers[i] << " ";
            only_numbers.push_back(int(chars_and_numbers[i]));
        }
    }

    cout << endl;

    for (vector<int>::iterator i = only_numbers.begin(); i != only_numbers.end(); i++) {
        cout << *i << " ";
    }

    return 0;
}

Output:

1 2 3 4 5 6 7 8 9 0
49 50 51 52 53 54 55 56 57 48
like image 542
Tiago Avatar asked Mar 16 '26 21:03

Tiago


1 Answers

ASCII Character    ASCII Code(decimal)  Literal Integer
      '0'               48                      0
      ...               ...                    ...
      '9'               57                      9

int(chars_and_numbers[i]) returns you the underlying ASCII code of ASCII character instead of the literal integer what you want.

Generally, 'i' - '0' results in i if i belongs to [0, 9].

E.g., '1' - '0' returns you the distances between values of two ASCII characters(49 - 48), which is 1.

int main() {
    string chars_and_numbers = "123a456b789c0";
    vector<int> only_numbers;

    for (int i = 0; i < chars_and_numbers.length(); i++) {
        if (isdigit(chars_and_numbers[i])) {
            cout << chars_and_numbers[i] << " ";
            // here is what you want
            only_numbers.push_back(chars_and_numbers[i] - '0');
        }
    }

    cout << endl;

    for (vector<int>::iterator i = only_numbers.begin(); i != only_numbers.end(); i++) {
        cout << *i << " ";
    }

    return 0;
}
like image 103
Eric Z Avatar answered Mar 19 '26 11:03

Eric Z