在本教程中,我们将讨论一个程序,以了解如何在C / C ++中将字符串转换为整数数组。
为此,我们将创建一个新数组。遍历给定的字符串,如果字符是逗号“,”,则继续下一个字符,否则将其添加到新数组中。
#include <bits/stdc++.h> using namespace std; //将字符串转换为整数数组 void convert_array(string str){ int str_length = str.length(); int arr[str_length] = { 0 }; int j = 0, i, sum = 0; //遍历字符串 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; }
输出结果
arr[] = 1569522526 Sum of array is = 1569522526