Problem statement:
Given a string consisting of space-separated integers, we need to extract those integers and perform some operations on them.
Sample Input:
The input consists of a single string containing space-separated integers.
23 4 56 789
Sample Output:
Print the sum of the integers and a string that concatenates the integers together.
872
23456789
Explanation:
In this example, the input string is "23 4 56 789". We need to extract the integers from the string and perform the following operations:
Calculate the sum of the integers: 23 + 4 + 56 + 789 = 872
Concatenate the integers together: "23" + "4" + "56" + "789" = "23456789"
#include <iostream>
#include <sstream>
using namespace std;
int main() {
string input;
getline(cin, input);
stringstream ss(input); // Create a stringstream object with the input string
int num;
int sum = 0;
string concatenated;
// Extract integers from the stringstream and perform operations
while (ss >> num) {
sum += num; // Calculate the sum
concatenated += to_string(num); // Concatenate the integers
}
cout << sum << endl;
cout << concatenated << endl;
return 0;
}
Code Explanation
Explanation of the Solution:
We start by reading the input string using getline(cin, input).
We create a stringstream object called ss with the input string. This allows us to perform operations on the individual integers within the string.
We define an integer variable num to store the extracted integers.
We also define an integer variable sum to calculate the sum of the integers and a string variable concatenated to concatenate the integers together.
We enter a while loop that runs as long as there are integers left to extract from the stringstream.
Inside the loop, we use ss >> num to extract the next integer from the stringstream and store it in num.
We update the sum by adding the extracted integer to it.
We update the concatenated string by converting the extracted integer to a string using to_string(num) and appending it to the string.
After extracting all the integers and performing the operations, we print the sum and concatenated string using cout.
Finally, we return 0 to indicate successful program execution.
This solution utilizes the stringstream class in C++ to extract integers from the input string and perform operations on them. It calculates the sum of the integers and concatenates them together as required by the problem statement.
I hope this solution and explanation are helpful!