Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,895 questions

51,826 answers

573 users

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 76 views
1 answer 74 views
2 answers 232 views
1 answer 102 views
...