In this program, we are going to share a how to convert a string to integer array in CPP with the output. If you are a beginner and want to start learning the C++ programming, then keep your close attention in this tutorial as I am going to share how to convert a string to integer array in CPP with the output.
Copy the below C++ program and execute it with the help of GCC compiler. At the end of this program, We have shared the output of this program.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 |
#include <bits/stdc++.h> using namespace std; void convertStrtoArr(string str) { // get length of string str int str_length = str.length(); // create an array with size as string // length and initialize with 0 int arr[str_length] = { 0 }; int j = 0, i, sum = 0; // Traverse the string for (i = 0; str[i] != '\0'; i++) { // if str[i] is ', ' then split if (str[i] == ', ') { // Increment j to point to next // array location j++; } else { // subtract str[i] by 48 to convert it to int // Generate number by multiplying 10 and adding // (int)(str[i]) arr[j] = arr[j] * 10 + (str[i] - 48); } } cout << "arr[] = "; for (i = 0; i <= j; i++) { cout << arr[i] << " "; sum += arr[i]; // sum of array } // print sum of array cout << "\nSum of array is = " << sum << endl; } // Driver code int main() { string str = "2, 6, 3, 14"; convertStrtoArr(str); return 0; } |
arr[] = 2 6 3 14
Sum of array is = 25
If you like FreeWebMentor and you would like to contribute, you can write an article and mail your article to [email protected] Your article will appear on the FreeWebMentor main page and help other developers.