Using C++ Write a command line calculator in C++. The calculator supports the fo
ID: 3877896 • Letter: U
Question
Using C++
Write a command line calculator in C++. The calculator supports the following mathmatical operations:
• Multiplication m
• Divison d
• Subtraction s
• Addition a
• Percentage p
The following example show cases how this calculator can be used
The calculator should also support a commandline option --history, which displays the list of all previous calculations. Check out the following example:
$ ccalc p 2 10 Ans: 20
$ calc --history History:
p 2 10
20
a23
5
m 2 40
80
By necessity you’ll have to use a file to save/load the history. For the purposes of this exercise, lets assume that the history is stored in file ccalc-history.txt sitting in the local directory.
Explanation / Answer
#include <iostream.h>
#include <string.h>
#include <stdlib.h>
#include <conio.h>
#include <stdio.h>
#include <ctype.h>
//using namespace std;
FILE *fp;
char str[10];
void add(int a,int b){
int r;
r=a+b;
cout<<r;
sprintf(str,"a %d %d %d ",a,b,r);
fwrite(&str,sizeof(str),1,fp);
}
void sub(int a,int b){
int r;
r=a-b;
cout<<r;
sprintf(str,"s %d %d %d ",a,b,r);
fwrite(&str,sizeof(str),1,fp);
}
void mul(int a,int b){
int r;
r=a*b;
cout<<r;
sprintf(str,"m %d %d %d ",a,b,r);
fwrite(&str,sizeof(str),1,fp);
}
void divi(int a,int b){
int r;
r=a/b;
cout<<r;
sprintf(str,"d %d %d %d ",a,b,r);
fwrite(&str,sizeof(str),1,fp);
}
int main(int argc, char *argv[] ) {
char op;
char *test;
int val1,val2;
clrscr();
test=argv[1];
if(*(test+1)==0) {
op=*argv[1];
val1=atoi(argv[2]);
val2=atoi(argv[3]);
fp=fopen("ccalchistory.txt","a+");
cout<<val1<<" "<<val2<<endl;
switch(op)
{
case 'a':
case 'A': add(val1,val2); break;
case 's':
case 'S': sub(val1,val2); break;
case 'm':
case 'M': mul(val1,val2); break;
case 'd':
case 'D': divi(val1,val2); break;
default: cout<<"invalid input";
}
}
else if(!strcmp("--history",argv[1])){
if(fp=fopen("ccalchistory.txt","r")){
char ch1;
ch1=getc(fp);
while(ch1!=EOF){
cout<<ch1;
ch1=getc(fp);
}
}
else{
printf("no history");
}
}
else{
cout<<"invalid input";
}
fclose(fp);
getch();
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.