Need help writing this program in C Not allowed to use a loo
Need help writing this program in C++. Not allowed to use a looping structure, but I do have to use a switch statement and include a check for an invalid operator [idk what that last one is really]). Anything helps, been working on it forever.
Solution
Dear Asker,
This problems asks you to read arithematic statements (like 2 + 4, 5 / 3.0, 6*7, 89-67, only multiplication,division addtion and substractions are allowed) and write the output into a file. The input is of the form \'operand1 operator operand2\', mind the space between them, they will become very useful in extracting the operator.
There is no need to use looping structure in this problem, because C++ has rich inbuilt library to be used.
Following code should give you some clue to solve this problem, remeber to replace \'?\' with valid values.
#include <cstdlib>
#include <iostream>
#include <string>
#include <fstream>
using namespace std;
int main()
{
ofstream outputfile;
//you should initialize the outputfilename variable
string s, outputfilename = \"cheggtest.txt\";
//try to open output file
try
{
outputfile.open(outputfilename);
}catch(exception const& e)
{
cout<<\"Error opening file: \"<<e.what()<<endl;
//exit the program
return 1;
}
outputfile<<\"Author\\\'s Name\ \"
<<\"C.S.1428.?\ \"
<<\"Lab Section: L?\ \"
<<\"--/--/--\ \";
cout<<\"Enter a binary expression of the form: operand operator operand \ \ \"
<<\"Author\\\'s Name\ \"
<<\"C.S.1428.?\ \"
<<\"Lab Section: L?\ \"
<<\"--/--/--\ \"
<<\"The name of the output file is\"<<outputfilename<< endl;
//take input operator and operands
getline(cin,s);
//try to find the operator
int index = s.find(\" \");
char op = s[index+1];
//extract the operands
double op1 = atof(s.substr(0,index).c_str());
double op2 = atof(s.substr(index+3).c_str());
switch(op)
{
case \'/\':
if(op2==0)
{
outputfile<<s<<\" Division by zero produces an undefined result\";
cout<<\"Division by zero produces an undefined result\";
}
else
{
outputfile<<s<<\" = \"<<(op1/op2);
cout<<s<<\" = \"<<(op1/op2);
}
break;
case \'*\':
outputfile<<s<<\" = \"<<(op1*op2);
cout<<s<<\" = \"<<(op1*op2);
break;
case \'+\':
outputfile<<s<<\" = \"<<(op1+op2);
cout<<s<<\" = \"<<(op1+op2);
break;
case \'-\':
outputfile<<s<<\" = \"<<(op1-op2);
cout<<s<<\" = \"<<(op1-op2);
break;
default:
cout<<\"The operator is not recognized\";
}
outputfile.close();
}

