Two variables store strings that consist of a string of 1to 2 alphabets, a blank
ID: 3677845 • Letter: T
Question
Two variables store strings that consist of a string of 1to 2 alphabets, a blank space, and a number (for example, in the form ‘AR 14.3’). Write a function that would receive two such strings as input arguments. Then, the function will use string manipulating functions to extract the numbers from the strings, add them together, and return the sum as the output argument. For example, if the two strings are: str1 = 'Jk 8.23'; str2 = 'M 24.4'; A call to the function AddString(str1, str2) would return the result: 32.63
Explanation / Answer
#include <iostream>
#include <string>
#include <stdlib.h>
using namespace std;
float AddString(string str1,string str2){
size_t found = str1.find(" ");
string str1_num = str1.substr(found+1);
found = str2.find(" ");
string str2_num = str2.substr(found+1);
size_t sz; // alias of size_t
float num1 = atof(str1_num.c_str());
float num2 = atof(str2_num.c_str());
return num1+num2;
}
int main() {
string str1 = "Jk 8.23";
string str2 = "M 24.4";
cout<<AddString(str1, str2);
return 0;
}
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.