Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Convert a String to Integer Array in C/C++
In this tutorial, we will be discussing a program to understand how to convert a string into integer array in C/C++.
For this we will create a new array. Traverse through the given string, if the character is a comma “,”, we move on to the next character else add it to the new array.
Example
#include <bits/stdc++.h>
using namespace std;
//converting string to integer array
void convert_array(string str){
int str_length = str.length();
int arr[str_length] = { 0 };
int j = 0, i, sum = 0;
//traversing the string
for (i = 0; str[i] != '\0'; i++) {
if (str[i] == ', ') {
j++;
}
else {
arr[j] = arr[j] * 10 + (str[i] - 48);
}
}
cout << "arr[] = ";
for (i = 0; i <= j; i++) {
cout << arr[i] << " ";
sum += arr[i];
}
cout << "\nSum of array is = " << sum << endl;
}
int main(){
string str = "2, 6, 3, 14";
convert_array(str);
return 0;
}
Output
arr[] = 1569522526 Sum of array is = 1569522526
Advertisements