Two variables store strings that consist of a string of 1to 2 alphabets, a blank
ID: 3677883 • 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
Program plan:As mentioned in the question the user should take two string variables and then by using string manipulation functions user should add the values in the given string and return the value as a return argument to the called function.hence we need to implement the addString function which takes two strings as arguments and returns the sum of numbers in the given string.
Program:
//including library functions
#include<iostream.h>
#include<conio.h>
#include<string.h>
#include<stdio.h>
#include<stdlib.h>
float addString(char str1[30],char str2[30]); //function declaration
void main()
{
char str1[30],str2[30];
float sum;
clrscr();
cout<<"Enter a string:(only in the form of AR 14.3) ";
gets(str1);
cout<<"Enter another string: ";
gets(str2);
sum=addString(str1,str2);//function calling
cout<<"The value is :"<<sum;
getch();
}
//function definition
float addString(char str1[30],char str2[30])
{
float a,b;
/*for loop is used to identify the space and after space we have the number value and hence we subtract the remaining string by using substr method and uses atf function to convert the string value to float variable*/
for(int i=0;i<strlen(str1);++i)
{
if(isspace(str1[i])) break;
}
a=atof(substr(i,strlen(str1)));
for(int j=0;j<strlen(str2);++i)
{
if(isspace(str2[j]) )break;
}
b=atof(substr(j,strlen(str2)));
return(a+b);
}
sample output:
Enter a String:(only in the form of AR 14.3)
BR 5.3
Enter another String :
ac 5.6
The value is 10.9
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.