Write a C++ program to find the numbers in a given string and calculate the sum of all numbers

  • برمجة سي بلس بلس
  • برمجة

Write a C++ program to find the numbers in a given string and calculate the sum of all numbers

Sample Output:

Original string: 91, ABC Street.-> Sum of the numbers: 91
Original string: w3resource from 2008->  Sum of the numbers: 2011
Original string: C++ Versiuon 14aa11bb23->  Sum of the numbers: 48

الأجوبة

#include <iostream>
#include <string>

using namespace std;

int find_nums_and_sum(string str) {

	int sum_num = 0;
	string temp_str;

	for (int x = 0; x < str.length(); x++)
	{
		if (isdigit(str[x]))
		{
			temp_str.push_back(str[x]);

			for (int y = x + 1; y < str.length(); y++)
			{
				if (y >= str.length())
				{
					break;
				}
				else if (isdigit(str[y]))
				{
					temp_str.push_back(str[y]);
					x = y;
				}
				else
				{
					break;
				}
			}

			sum_num += stoi(temp_str);
			temp_str.clear();
		}
	}

	return sum_num;
}

int main() {

	cout << "Original string: 91, ABC Street.-> Sum of the numbers: "<< find_nums_and_sum("91, ABC Street.") << endl;
 	cout << "Original string: w3resource from 2008->  Sum of the numbers: "<< find_nums_and_sum("w3resource from 2008") << endl;
 	cout << "Original string: C++ Versiuon 14aa11bb23->  Sum of the numbers: "<< find_nums_and_sum("C++ Versiuon 14aa11bb23") << endl; 
	return 0;
}
هل كان المحتوى مفيد؟

تبحث عن مدرس اونلاين؟

محتاج مساعدة باختيار المدرس الافضل؟ تواصل مع فريقنا الان لمساعدتك بتأمين افضل مدرس
ماهو التخصص الذي تبحث عنه؟
اكتب هنا...