How to convert a number in a string to an array of int digits in C++

2 Answers

0 votes
#include <iostream>
  
void convert_number_in_string_to_array_of_int_digits(char str[], int arr[], int size) {
    for (int i = 0; i < size - 1; i++) {
        arr[i] = str[i] - '0';
    }
}
   
int main() {
    char str[] = "789";
    int arr[3] = { 0 };
    int size = sizeof(str) / sizeof(str[0]);
   
    convert_number_in_string_to_array_of_int_digits(str, arr, size);
   
    for (int i = 0; i < size - 1; i++) {
        std::cout << arr[i] << "\n";
    }
}
 
    
    
    
/*
run:
    
7
8
9
    
*/

 



answered Sep 30, 2024 by avibootz
edited Sep 30, 2024 by avibootz
0 votes
#include <iostream>
#include <vector>
#include <string>

std::vector<int> convert_number_in_string_to_array_of_int_digits(const std::string& str) {
    std::vector<int> digits;
    for (char ch : str) {
        if (isdigit(ch)) {
            digits.push_back(ch - '0'); // Convert char to int
        }
    }
    return digits;
}

int main() {
    std::string number = "7859";
    std::vector<int> digits = convert_number_in_string_to_array_of_int_digits(number);

    for (int digit : digits) {
        std::cout << digit << " ";
    }
    std::cout << std::endl;
}

   
   
/*
run:
   
7 8 5 9 
   
*/

 



answered Sep 30, 2024 by avibootz

Related questions

2 answers 111 views
1 answer 98 views
2 answers 269 views
1 answer 129 views
...