Here is my justification for my comments above where I say
isdigit
will work (when it is used properly).
In this case you have
Quote:
And sample input should be hardcoded and should display as given above
In most cases (or as you move through your course) inputs will come from the command line (or parameters) in which case it is safe to assume any key can be used ... so handle
string
s.
Lusvardi has given a good example of how to do this.
My snippet below is intended to show you how
isdigit
would work in this instance - see the function
ValidNum
#include<iostream>
#include<string>
using namespace std;
void ProcessSample(string num1, string num2);
bool ValidNum(string num);
void OutputResult(int num1, int num2);
void main(){
ProcessSample("3","1");
ProcessSample("a","b");
ProcessSample("1","b");
ProcessSample("23","101");
cout << "Hit a key to end";
getchar();
return;
}
void ProcessSample(string num1, string num2)
{
if(ValidNum(num1) && ValidNum(num2))
cout << "Result: " << stoi(num1) + stoi(num2) << endl;
else
cout << "Invalid Input" << endl;
}
bool ValidNum(string num)
{
bool ret = true;
for(int i = 0; i < num.length(); i++)
if(!isdigit(num[i])) ret = false;
return ret;
}