In: Computer Science
Write a C++ function template to add two inputs and return their result. Make exceptions for Characters (such that sum of two characters is a character associated with sum of their ASCII) and String (such that sum of two strings is their concatenation)
In the given question, it is asked to write a C++ function template to
1) Add two numbers, if it is integer
2) Sum of ASCII values to represent a character, if both are Char
3)Concatenation, if it is a string.
The C++ code including main() and function template for the following question will looklike
#include <iostream>
#include<string>
#include<cstring>
#include<bits/stdc++.h>
using namespace std;
bool isNumber(string s) // function to check if string is integer.
{
for (int i = 0; i < s.length(); i++)
if (isdigit(s[i]) == false)
return false;
return true;
}
string getString(char x)
{
string s(1, x);
return s;
}
string templa(string inp1, string inp2)
{
if (isNumber(inp1))
{
int num1,num2,num3;
num1 = std::stoi(inp1);
num2 = std::stoi(inp2);
num3 = num1 + num2;
std::string strnum = to_string(num3);
cout<<"The sum is ";
return strnum;
}
else
{
int len1,len2;
len1=inp1.length();
len2=inp2.length();
if(len1==1 && len2==1)
{
int cnum1,cnum2,cnum3;
char char_array1[1], char_array2[1],c1,c2;
unsigned char c3;
string ascich;
strcpy(char_array1, inp1.c_str());
strcpy(char_array2, inp2.c_str());
c1 = char_array1[0];
c2 = char_array2[0];
cnum1 = int(c1);
cnum2 = int(c2);
cnum3 = cnum1 + cnum2;
c3 = static_cast<char>(cnum3);
cout<<"The ASCII value is "<<cnum3;
ascich = getString(c3);
cout<<" The string is ";
return ascich;
}
else
{
string full;
full = inp1 + inp2;
cout<<"The Concatenation is ";
return full;
}
}
}
int main()
{
string inp1,inp2;
string out3;
cin>>inp1;
cin>>inp2;
out3=templa(inp1,inp2);
cout<<out3;
return 0;
}
Here templa() is the template function.
isNumber() is used to check if a string is number or not.
getString() is used to convert char to string.
Depending on the complier, the extended ASCII character may or may not be printed.
However, all the ASCII characters, as asked in the question will be printed.
Hope, this answer helps.