I have been able to use selection structure to complete my program only need advice around this problem.
(how can i make an if statement that will show the user to put a number in case they typed a symbol of any sort).
Since num1 and num2 are initialized to 0.
#include %26lt;cstdlib%26gt;
#include %26lt;iostream%26gt;
#include %26lt;iomanip%26gt;
using namespace std;
int main (int argc, char*argv[])
{
int num1 = 0, num2 =0;
char ch1 = '+';
char ch2 = '=';
cout %26lt;%26lt; " Wellcome to the calculation" %26lt;%26lt; endl;
cout %26lt;%26lt; " Enter your equation as number operation number" %26lt;%26lt; endl;
cout %26lt;%26lt; " (Example: 3 + 4): ";
cin %26gt;%26gt; num1 %26gt;%26gt; ch1 %26gt;%26gt; num2 %26gt;%26gt; ch2;
if ( ch1 != '+')
cout %26lt;%26lt; "You must place the + sign after the number" %26lt;%26lt; endl;
if ( ch2 != '=')
cout %26lt;%26lt; "You must place the = sign after the number" %26lt;%26lt; endl;
// I need an if statemnt that tells the user to put a number if
// they were to make the mistake of putting a simbol in the place of a
// number
else
cout %26lt;%26lt; num1 %26lt;%26lt; "+" %26lt;%26lt; num2 %26lt;%26lt; "=" ;
cout %26lt;%26lt; num1 + num2 %26lt;%26lt; endl;
system ("pause");
return 0;
}
Need a help with a little program in C++?
OK... took me a while... How about this:
int _tmain(int argc, _TCHAR* argv[])
{
bool bad = false;
char nm1[10];
char nm2[10];
int num1 = 0, num2 =0;
char ch1 = '+';
char ch2 = '=';
cout %26lt;%26lt; " Wellcome to the calculation" %26lt;%26lt; endl;
cout %26lt;%26lt; " Enter your equation as number operation number" %26lt;%26lt; endl;
cout %26lt;%26lt; " (Example: 3 + 4): ";
cin %26gt;%26gt; nm1 %26gt;%26gt; ch1 %26gt;%26gt; nm2 %26gt;%26gt; ch2;
if ( ch1 != '+'){
cout %26lt;%26lt; "You must place the + sign after the number" %26lt;%26lt; endl;
bad = true;
}
if ( ch2 != '='){
cout %26lt;%26lt; "You must place the = sign after the number" %26lt;%26lt; endl;
bad = true;
}
// I need an if statemnt that tells the user to put a number if
// they were to make the mistake of putting a simbol in the place of a
// number
int i;
for (i=0; ((nm1[i]!=0)%26amp;%26amp;(nm1[i]%26gt;='0')%26amp;%26amp;(nm1[i]%26lt;='9... i++);
if (nm1[i] != 0){
//bad number
cout %26lt;%26lt; "First number is invalid" %26lt;%26lt; endl;
bad = true;
}
num1 = atoi(nm1);
for (i=0; ((nm2[i]!=0)%26amp;%26amp;(nm2[i]%26gt;='0')%26amp;%26amp;(nm2[i]%26lt;='9... i++);
if (nm2[i] != 0){
//bad number
cout %26lt;%26lt; "Second number is invalid" %26lt;%26lt; endl;
bad = true;
}
if (!bad){
num2 = atoi(nm2);
cout %26lt;%26lt; num1 %26lt;%26lt; "+" %26lt;%26lt; num2 %26lt;%26lt; "=" ;
cout %26lt;%26lt; num1 + num2 %26lt;%26lt; endl;
}
system ("pause");
return 0;
}
Reply:you have the template right there
if ( ch1 != '+')
cout %26lt;%26lt; "You must place the + sign after the number" %26lt;%26lt; endl;
do this
if ( num1 == '+')
cout %26lt;%26lt; "You must place a number there" %26lt;%26lt; endl;
you could do that for all possible chars that are not numbers, that would be alot, or you could look up the ascii codes for the numbers and test each char for the correct range to be a number
Reply:// ----------------------------------------...
// add/subtract/multiply/divide two numbers together
//
// Think about the steps:
// 1) get the input
// 2) parse up the input into a series of tokens
// 3) validate the tokens
// 4) perform the operation on the tokens
// 5) print the result
//
// Usually error handling takes more code than
// the success path. For example....
// ----------------------------------------...
#include %26lt;iostream%26gt;
#include %26lt;string%26gt;
#include %26lt;stdlib.h%26gt;
using namespace std;
// ----------------------------------------...
static const size_t MAX_TOKENS = 3;
static const size_t MAX_STRING = 256; //includes NULL
static const size_t EXPECT_NUM_TOKENS = 3;
static const size_t FIRST_NUMBER_TOKEN = 0;
static const size_t OPERATOR_TOKEN = 1;
static const size_t SECOND_NUMBER_TOKEN = 2;
static const string whitespaceChars = " \t\n";
static const string numberChars = "0123456789";
static const string operatorChars = "+-*/";
// ----------------------------------------...
// Display a greeting
void greeting( void)
{
cout %26lt;%26lt; "Simple calculator" %26lt;%26lt; endl;
cout %26lt;%26lt; "Syntax: number operator number" %26lt;%26lt; endl;
cout %26lt;%26lt; "For example: 3 + 4" %26lt;%26lt; endl;
cout %26lt;%26lt; "Use q to quit" %26lt;%26lt; endl %26lt;%26lt; endl;
}
// ----------------------------------------...
// Get the input string that is to be processed
void getInput( string %26amp;inputStr )
{
cout %26lt;%26lt; "%26gt; ";
char str[MAX_STRING];
cin.getline( str, MAX_STRING );
inputStr = str;
}
// ----------------------------------------...
// Dump a string to the screen for debugging
void dumpString( const string%26amp; str )
{ // The less than and greater than signs will highlight leading
// and trailing whitespace
cout %26lt;%26lt; "%26gt;" %26lt;%26lt; str %26lt;%26lt; "%26lt;" %26lt;%26lt; endl;
}
// ----------------------------------------...
// Dump an array of token strings
void dumpTokens( const string tokens[], const size_t numTokens )
{
for( size_t i=0; i %26lt; numTokens; i++ )
{
dumpString( tokens[i] );
}
}
// ----------------------------------------...
// Parse a string into a series of tokens
// Params: inputStr - string to be parsed
// token - array of strings to receive the tokens. maxTokens
// in size.
// maxTokens - maximum number of tokens that can be placed in "tokens"
// numTokens - number of tokens extracted from string.
// errorStr - description of error if encountered.
// Returns: true - if tokens extracted successfully.
// false - if an error is encountered.
//
bool tokenize(
const string%26amp; inputStr,
string token[],
const size_t maxTokens,
size_t%26amp; numTokens,
string%26amp; errorStr
)
{
// A tokens will be split based on whitespace
numTokens = 0;
// Skip leading whitespace
size_t startPos = 0;
for( ;; )
{
startPos = inputStr.find_first_not_of(whitespaceCha... startPos );
if( startPos == string::npos )
{ // Hit the end of the input
break;
}
// Hunt for first non-whitespace to delineate a token
size_t endPos = inputStr.find_first_of(whitespaceChars, startPos);
if( endPos == string::npos )
{ // Hit the end of input
token[numTokens]=inputStr.substr(startPo...
}
else
{
token[numTokens]=inputStr.substr(startPo... endPos-startPos );
}
startPos = endPos;
numTokens++ ;
}
if( numTokens == 0 )
{
errorStr = "ERROR: No input found";
return false;
}
return true;
}
// ----------------------------------------...
// Validate that the tokens are of the right type and number.
// Params: token - array of strings to containing the tokens.
// numTokens - number of tokens passed in.
// errorStr - description of error if encountered.
// Returns: true - if tokens are valid
// false - if an error is encountered.
//
bool validateTokens(
const string token[],
const size_t numTokens,
string%26amp; errorStr
)
{
// Check for q (i.e. quit)
if( numTokens == 1 %26amp;%26amp; token[0][0] == 'q' )
{ // Wants to quit, so let it through
return true;
}
if( numTokens %26lt; EXPECT_NUM_TOKENS )
{
errorStr = "ERROR: Incomplete expression";
return false;
}
if( numTokens %26gt; EXPECT_NUM_TOKENS)
{
errorStr = "ERROR: Expression too long";
return false;
}
// We have the right number of tokens but are they the right
// type and in the right order.
// You have to deal with unary + -
size_t startPos = 0;
if( token[FIRST_NUMBER_TOKEN][startPos] == '-' ||
token[FIRST_NUMBER_TOKEN][startPos] == '+' )
{
startPos = 1;
}
if( token[FIRST_NUMBER_TOKEN].find_first_of(... == string::npos )
{
errorStr = "ERROR: Expected number got %26gt;";
errorStr += token[FIRST_NUMBER_TOKEN];
errorStr += "%26lt;";
return false;
}
// A single character operator is next
if( token[OPERATOR_TOKEN].find_first_of(oper... == string::npos ||
token[OPERATOR_TOKEN].length() != 1 )
{
errorStr = "ERROR: Expected operator got %26gt;";
errorStr += token[OPERATOR_TOKEN];
errorStr += "%26lt;";
return false;
}
// You have to deal with unary + -
startPos = 0;
if( token[SECOND_NUMBER_TOKEN][startPos] == '-' ||
token[SECOND_NUMBER_TOKEN][startPos] == '+' )
{
startPos = 1;
}
if( token[SECOND_NUMBER_TOKEN].find_first_of... == string::npos )
{
errorStr = "ERROR: Expected number got %26gt;";
errorStr += token[SECOND_NUMBER_TOKEN];
errorStr += "%26lt;";
return false;
}
return true;
}
// ----------------------------------------...
// Calculate the result given a number-operator-number set.
// Params: token - array of strings to containing the tokens.
// numTokens - number of tokens passed in.
// errorStr - description of error if encountered.
// Returns: true - if calculation was successful
// false - if an error is encountered.
//
bool calculate(
const string token[],
const size_t numTokens,
long int%26amp; result,
string%26amp; errorStr
)
{
int firstNumber = atoi( token[FIRST_NUMBER_TOKEN].c_str() );
if( firstNumber == INT_MAX || firstNumber == INT_MIN )
{
errorStr = "ERROR: Number out of range: %26gt;";
errorStr += token[FIRST_NUMBER_TOKEN];
errorStr += "%26lt;";
return false;
}
int secondNumber = atoi( token[SECOND_NUMBER_TOKEN].c_str() );
if( secondNumber == INT_MAX || secondNumber == INT_MIN )
{
errorStr = "ERROR: Number out of range: %26gt;";
errorStr += token[SECOND_NUMBER_TOKEN];
errorStr += "%26lt;";
return false;
}
switch( token[OPERATOR_TOKEN][0] )
{
case '+':
if( firstNumber == 2 %26amp;%26amp; secondNumber == 2 )
{
cout %26lt;%26lt; "-------------------------------" %26lt;%26lt; endl;
cout %26lt;%26lt; "2+2=5" %26lt;%26lt; endl;
cout %26lt;%26lt; "For extremely large values of 2" %26lt;%26lt; endl;
cout %26lt;%26lt; "------------www.thinkgeek.com--" %26lt;%26lt; endl;
}
result = firstNumber + secondNumber;
break;
case '-':
result = firstNumber - secondNumber;
break;
case '*':
result = firstNumber * secondNumber;
break;
case '/':
if ( secondNumber == 0 )
{
errorStr = "ERROR: Divide by zero not allowed.";
return false;
}
result = firstNumber / secondNumber;
break;
default:
errorStr = "ERROR: Unexpected operator";
return false;
}
return true;
}
// ----------------------------------------...
int main( int argc, char* argv[] )
{
greeting();
for( ;; )
{
// Step 1) get the input
string inputStr;
getInput( inputStr );
// Step 2) parse up the input into a series of tokens
string tokens[MAX_TOKENS];
size_t numTokens = 0;
string errorStr;
if (!tokenize( inputStr, tokens, MAX_TOKENS, numTokens, errorStr ) )
{
cout %26lt;%26lt; errorStr %26lt;%26lt; endl;
continue; // go back around for another try
}
//dumpTokens( tokens, numTokens );
// Step 3) validate the tokens
if( !validateTokens( tokens, numTokens, errorStr ) )
{
cout %26lt;%26lt; errorStr %26lt;%26lt; endl;
continue; // go back around for another try
}
if( numTokens == 1 )
{ // Can only have one token if its the quit token
cout %26lt;%26lt; "Quitting..." %26lt;%26lt; endl;
exit(0); // Successful exit
}
// Step 4) calculate the result
long int result = 0;
if( !calculate( tokens, numTokens, result, errorStr ) )
{
cout %26lt;%26lt; errorStr %26lt;%26lt; endl;
continue; // go back around for another try
}
// Step 5) output the result
cout %26lt;%26lt; result %26lt;%26lt; endl;
}
}
Reply:Use the ascii number reference, Im on a train without the ref with me and about to go through a tunnel by pseudo code ...
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment