Hello everyone. I recently started using C++ and blah blah blah you know the rest.

Using my extremely limited knowledge, I attempted to make a basic 4 function calculator CUI in C++. The code I wrote is as follows.

#include <iostream>
#include <string>
#include <sstream>
using namespace std;

char operator -;
char operator +;
char operator *;
char operator /;
int myoperator;
float num1;
float num2;
float result;

int mainproc ()
{
	cout << "Welcome to the 4-Basic-Calculator!\nEnter first number: ";
	cin >> num1;
	cout << "\nEnter the operator: ";
	cin >> operator;
	if(operator == "+")
		myoperator = 1;
	if(operator == "-")
		myoperator = 2;
	if(operator == "*")
		myoperator = 3;
	if(operator == "/")
		myoperator = 4;
	if(operator != "+" || "-" || "*" || "/")
		{
			cout << "You fail";
			system("PING LOCALHOST -5 >nul");
			return 0;
		}
	cout << "\nEnter second number: ";
	cin >> num2;
	if(myoperator == 1)
		result = num1 + num2;
	if(myoperator == 2)
		result = num1 - num2;
	if(myoperator == 3)
		result = num1 * num2;
	if(myoperator == 4)
		result = num1 / num2;
	cout << \nresult << "\nThank you for using the 4-Basic-Calculator coded by Gimper and Foteye! Coming soon - A repeat function!";
	system("PAUSE");
	return 0;
}

From what I can see it should work, but I keep getting these 2 build errors.

c:\documents and settings\luke\my documents\visual studio 2008\projects\calculator\calculator\calculator.cpp(20) : error C2833: 'operator ;' is not a recognized operator or type

and

c:\documents and settings\luke\my documents\visual studio 2008\projects\calculator\calculator\calculator.cpp(20) : error C2059: syntax error : 'newline'

Can someone please explain to me where I've gone wrong and how to fix it? And of course, if it isn't too much trouble, fix the code? Thanks in advance :)

There are *a lot* of things wrong with this code, so instead pointing them all out, I've changed your code and commented on what I've changed:

#include <iostream>
//#include <string> //don't need it
//#include <sstream> // don't need it
using namespace std;

// You don't want to declare stuff in global scope:

/*char operator -;
char operator +;
char operator *;
char operator /;
int myoperator;
float num1;
float num2;
float result;*/

// mainproc does not exist. Your program ALWAYS needs a main()
//int mainproc () 
int main()
{
    char oper; // declare the char here, instead of global. 
    // Also don't use 'operator' as a name, because it's a C++ keyword!!
    int num1 = 0, myoperator = 0, num2 = 0, result = 0;  //declare integers here instead of global  and give initial value
    cout << "Welcome to the 4-Basic-Calculator!\nEnter first number: ";
    cin >> num1;
    cout << "\nEnter the operator: ";
    cin >> oper;
    if(oper == '+') // use single quotes for a single char!
        myoperator = 1;
    else if(oper == '-') // use single quotes for a single char!
        myoperator = 2;
    else if(oper == '*') // use single quotes for a single char!
        myoperator = 3;
    else if(oper == '/') // use single quotes for a single char!
        myoperator = 4;
    //if(operator != "+" || "-" || "*" || "/") // VERY WRONG. Change to:
    else 
    {
        cout << "You fail";
       // system("PING LOCALHOST -5 >nul"); // Not amused.
        return 0;
    }
    cout << "\nEnter second number: ";
    cin >> num2;
    if(myoperator == 1)
        result = num1 + num2;
    if(myoperator == 2)
        result = num1 - num2;
    if(myoperator == 3)
        result = num1 * num2;
    if(myoperator == 4)
        result = num1 / num2;
    // put quotes around newline
    cout << '\n' << result << "\nThank you for using the 4-Basic-Calculator coded by Gimper and Foteye! Coming soon - A repeat function!";
   // system("PAUSE"); // Don't use this... Use this instead:
    cin.ignore();
    cin.get();
    return 0;
}

note: this isn't tested, so it might still have a few bugs in it. But it should get you started!

[edit] And you're logic is a bit off. Why do you use a myoperator anyway? Think about it and look closely at the 'ifs' in your program :)

Im no expert but couldnt you make this code half the size by doing a little condencing. Try something like this...

#include <iostream>

      #include <string>

      #include <sstream>

      using namespace std;
      

      int mainproc ()

      {
      char operator;

     float num1=0;

     float num2=0;

      float result=0;
  
      cout << "Welcome to the 4-Basic-Calculator!\nEnter first number: ";
  
      cin >> num1;
 
      cout << "\nEnter the operator: ";
  
      cin >> operator;

	cout << "Enter second number: "
	cin >> num2;
      
      if(operator == '+')

      result = num1 + num2;

      else if(operator == '-')

      result = num1 - num2;

      else if(operator == '*')

      result = num1 * num2;

      else if(operator == '/')

      result = num1 / num2;

	else      
      {

      cout << "You fail";

      return 0;

      }


      cout << '\n' << result << "\nThank you for using the 4-Basic-Calculator coded by Gimper and Foteye! Coming soon - A repeat function!";

      system("PAUSE");

     return 0;

      }

Thank you both so much for your input and help, especially you niek_e. This has actually furthered my knowledge of C++ significantly. I greatly appreciate it. :)

You can try this

#include<stdio.h>
#include<conio.h>
main()
{
clrscr();
	float a,b,d;
	char c;

printf("Enter the value of the first operand:");
	scanf("%f",&a);
printf("Enter the value of the second operand:");
	scanf("%f",&b);
printf("Enter the operator to be used:(+,-,*,/)");
	scanf("%s",&c);
{
	if(c=='+')
	{d=a+b;
printf("The sum of %f and %f is %.2f",a,b,d);}
	
else if(c=='-')
	{d=a-b;
printf("The difference of %f and %f is %.2f",a,b,d);}
	
else if(c=='*')
	{d=a*b;
printf("The product of %f and %f is %.2f",a,b,d);}
	
else if(c=='/')
	{d=a/b;
printf("The quotient of %f anf %f is %.2f",a,b,d);}
	}
getch();
}
commented: Why would you try to help in the C++ forum with bad C code? -3

yew, why conio? It is not standard and not even c++. It is c! And wtf is

#include <sstream>

Never heard of it. sounds like it was developed by nazis lol

^ Ummm wth? are u trying to get your post count up?? sstream is stringstream... you could easily have searched that up.. and you do know c++ and c are somewhat interchangeable right? U can import and export functions between them... It doesnt matter if it isnt pure/native c++

commented: please -- U is not a word. You s a word. This is not a chat room. -3

Hey guys,

Just wanted to share my improvements on the following code. Please let me know what you think :D Please bear in mind I've only been reading and coding for about a week !!

// Zarrens C++ Simple Calculator
// I decided to put everything I've learnt in the past few days to
// create this little simple calculator so I can practice my skills 
// as I improve, I will improve my calculator

// Header files
#include <cstdlib>
#include <cstdio>
#include <iostream>

using namespace std;


void Welcome_screen() {
   cout << "Weclome to Zarren's C++ Simple Calculator.\n";
   cout << "This is a little project that I will be improving as I improve ;)\n\n";
}

float input_check() {
  float num;
  while(1) {
    if (cin >> num) {
      break;
    }
    if(cin.fail()) {
      cout << "Numerical value needed !! Try again: ";
      cin.clear();
      cin.ignore( 1024, '\n' ); //spend a lot of time on this!
    }
  }
   return num;
}

float Plus    (float num1, float num2) { return num1+num2; }
float Minus   (float num1, float num2) { return num1-num2; }
float Multiply(float num1, float num2) { return num1*num2; }
float Divide  (float num1, float num2) { return num1/num2; }

int main() {
  char controller;
  float num1=0;
  float num2=0;
  char myoperator;
  float result=0;
  do { 
    Welcome_screen();
    cout << "Enter your first number: ";
    num1 = input_check();
    cout << "\nEnter the operator: ";
    cin >> myoperator;
    cout << "\nEnter second number: ";
    num2 = input_check();
    switch(myoperator) {
      case '+' : result = Plus     (num1, num2); break;
      case '-' : result = Minus    (num1, num2); break;
      case '*' : result = Multiply (num1, num2); break;
      case '/' : result = Divide   (num1, num2); break;
      default : cout << "Sorry, this is a BASIC calculator ;)\n";
    }
    cout << '\n' << result << "\n";
    cout << "Type any key and ENTER to contunue or Q ENTER to quit ...:";
    cin >> controller;
    system("clear");
  } while(controller != 'Q');
  cout << "Thanks for using my basic calculator !! \n Goodbye :D\n";
  return 0;
}

Really good for a beginner. But system("clear"); doesnt work. I don't know if it is on my system or you made a mistake. Why are you using it anyway? There is much better functions to clear screen

http://cplusplus.com Go there they have a wonderful tutorial that explains all the basics of C++ and C they also have plenty of examples.
By the way a calculator is what I always Develop when learning a new language after you feel comfortable with the basics try exporting the functions to a DLL and load them from there ...

Good luck!

You can use System("CLS"); to clear the screen.

And WaltP why would "you" put negative rep for me typing "u" instead of "You". If its a spelling class then fine.. whatever.

commented: Because U is not proper English and the rules state so -- and "U" bugs me no end! Don't be lazy... ;-) +15

Thanks guys :D the reason why I used system("clear") is because the system I use everyday has slackware linux installed as the main OS then I run several Virtual Machines for various things. clear is the equivalent to system("CLS") on a windows machine.

I know there are much more elegant ways to clear a shell and I'll more than likely improve on this calculator as I learn more :D. I'm still trying to get my head around pointer arithmetic :D

I just started to learn programming, and I've come across some guide etc. but as i was following one to make a calculator I think these lines are sure to come in hand.. Thank you.

check this one out, its the easiest and shortest one:

www.programmingtunes.com/a-simple-calculator-in-c/

what is the ouput of this codes

please can someone help me?
I have a similar task to write code for a simple calculator with square root, and M+(memory) functions.
I have been able to write out the code as with the square root but now i am stocked with how to include the memory function which will be able to store a result in the memory and be reused. I hope someone can help. my email is
mcprizo@yahoo.fr

here is my code;

#include <iostream>
#include<cmath>

using namespace std;
int main()
{

    double num1,num2;
    char operation,redo;

    cout<<"welcome to calculator program v.1.0 written by Kumson "<<endl;
 cout<<"..................................................................."<<endl;
    cout<<endl<<endl<<endl;
    do
    {

    cout<<"please enter an operation which you like to perform (+,-,*,/,^,s)\n";
    cout<<"[s stands for swap]:\n";
    cin>>operation;
    cout<<endl<<endl;
    cout<<"please enter two numbers to apply your requested operation(";
    cout<<operation<<"):\n"<<"1st num:";
    cin>>num1;
    cout<<"2nd num:";
    cin>>num2;
    cout<<endl;

    switch (operation)
    {


    case '+':
             cout<<"The addition of two numbers("<<num1<<","<<num2<<"):";
             cout<<num1+num2<<endl;
             break;
    case '-':
             cout<<"The difference of two numbers("<<num1<<","<<num2<<"):";
             cout<<num1-num2<<endl;
             break;
     case '*':
             cout<<"The product of two numbers("<<num1<<","<<num2<<"):";
             cout<<num1*num2<<endl;
             break;
    case '/':
             cout<<"The quotient of two numbers("<<num1<<","<<num2<<"):";
             if(num2==0)
             {
                 cout<<"not valid"<<endl;
             }
             cout<<(num1/num2)<<endl;
             break;
    case'^':
             cout<<"The squareroot of a number("<<num1<<"):\n";
             cout<<sqrt(num1)<<endl;
             break;
    case's':
            cout<<"The swap of two numbers("<<num1<<","<<num2<<"):";
             swap(num1,num2);
             cout<<"1stnumber="<<num1<<"and 2nd number="<<num2<<endl<<endl;
             break;
    default:
            cout<<"unknown command"<<endl;
    }


            cout<<"enter y or Y to continue:";
           cin>>redo;
           cout<<endl<<endl;
           }
           while(redo=='y'||redo=='Y');

   system("pause");
    return 0;

    }
// How can I rewrite this loop to C++ from C
// x, z, and v are vectors, and N is the number of vectors x and z (N=2).

c:= 10;     
N:= 2;          
p:= 3;

for r:= 1 to p do {
    sum(i:= 1 to N, v[i,r]) = 1;
    sum(i:= 1 to N, v[i,r]*z[i]) = zz[r];
    sum(i:= 1 to N, v[i,r]*x[i])  = value[r];

}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.