LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Newb C++ question (https://www.linuxquestions.org/questions/programming-9/newb-c-question-27138/)

Scotty2435 08-03-2002 06:14 PM

Newb C++ question
 
I have been trying to write a simple calculator program in c++ with my friend and ran into a problem

The calculator works by having the user input an operator (+ - / *) and then a number like this "+6"

The operator is a char variable and the number is a float variable

It goes into an infinite loop thing if the float variable is not a number, what code should i use to get it to output an error message and not crash when it does not get a number

Thanks

Eits0 08-03-2002 06:27 PM

try this one on problem point:
Code:

cin >> "n%";
else
 {
  cout << "Illegal operation! Forgive my sins, master!" << endl;
 }

:p
I'm n00b programmer, so don't listen to me.
But let meh see tah code... :jawa:
I'm not sure but doesn't the n% mean numeric value.
Don't listen to me, I've programmed only 11 days.

Mara 08-03-2002 06:42 PM

One of the methods:
1. Get the whole line (cin.getline(buffer, size) to a buffer with a safe size)
2. Check if first character in the buffer is one of +-*/. If it isn't, back to 1 (with a message like 'wrong number, enter again').
3.
Code:

for(int i=0;((buffer[i]>='0')&&(buffer[i]<='9')&&(buffer[i]!='\0'));i++) ;
if(buffer[i]!='.') cout <<"it's not a number";

4. if the last character was '.', do as in 3, but without checking for '.'

Of course, it's a good idea to add a function calculating value from characters into steps 3 and 4.
And the method isn't perfect, but I think it's clear.
You can use build in functins checking if it's a number etc.

Edit: It's 2 AM now, so there may be mistakes in the code. Forgive me :)

Scotty2435 08-03-2002 09:21 PM

Here is the source sorry if this is too long

#include <iostream.h>
#include <cmath>
#include <math.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

float result; // the result of the calculations
char oper_char; // the user-specified operator
float value; // value specified after the operator
float memory; // Memory (wanted to use an array but couldn't get to work)

main()
{
result = 0; // initialize the result
memory = 0;
//Program Intro
cout << "\n\nAndrew and Walton's Magnificent Calculator Program Now with MEMORY and INTEREST!!! \nPress 'h' for help menu\n\n";


// Loop forever (or until we hit the break statement)
while (1) {


//Print the result
cout << "Result: " << result << '\n';


cout << "Enter operator and number: ";

cin >> oper_char;


//Quit Statement


if ((oper_char == 'q') || (oper_char == 'Q'))
break;

//Help Menu
if ((oper_char == 'h')) {
cout << "\nHelp:\n";
cout << "Commands:
'Q' quit
's0' for square root
't0' for figuring tax amount (must enter rate)
'^power' to figure exponents
'c0' To clear all calculations and reset the result to '0'
'p0' To set result to pi.
'i0' To calculate interest
'r0' To work with right triangles
'm0' To copy the current result to memory
'p0' To display the stored number" ;
cout << "\n\nPress 'r' to return to program: ";
cin >> oper_char;
if ((oper_char == 'r')) {
continue;
}
}
cin >> value;

if (oper_char == '+') {
result += value;

} else if (oper_char == '-') {
result -= value;


//Store Something in Memory

} else if (oper_char == 'm') {
memory = result;

//Retrieve Memory

} else if (oper_char == 'p') {
cout <<"Stored Number: " << memory << '\n';

//Tangent doesn't work right needs help
} else if (oper_char == 'w') {
result = atan(result);

//Interest Program
} else if ((oper_char == 'i') || (oper_char == 'I')){
cout << "Enter Principle amount: ";
float principle;
cin >> principle;
cout << "Enter Interest Rate (ex.7.65): ";
float rate;
cin >> rate;
cout << "Enter Number of Years: ";
float year;
cin >> year;
result = principle*pow(rate/100+1,year);

} else if (oper_char == '*') {
result *= value;

//Change result to pi
} else if ((oper_char == 'p') || (oper_char == 'P')) {
result = 3.1415926535;

//Exponents
} else if (oper_char == '^') {
result = pow(result,value);

//Tax Program
} else if (oper_char == 't') {
cout << "Enter Tax Rate (ex.6.54): ";
float tax;
cin >> tax;
if (isalpha(tax)){
cout <<"You did not enter calculable numbers!!!\n\n";
break;
}else{
result = (tax/10)+1*result;
}
//Square Roots
}else if ((oper_char == 's') || (oper_char == 'S')) {
result = sqrt(result);

//Right Triangles
} else if ((oper_char == 'r') || (oper_char == 'R')) {
cout << "Do you want to find a missing side or determine if the triangleis right (s or r): ";

char option;
cin >> option;

//Determine if triangle is right
if (option == 'r') {
cout << "Enter Leg 1: ";
float leg1;
cin >> leg1;

cout << "Enter Leg 2: ";
float leg2;
cin >> leg2;

cout << "Enter Hypotenuse: ";
float hyp;
cin >> hyp;

if (pow(leg1,2) + pow(leg2,2) == pow(hyp,2)) {
cout << "It is a Right Triangle!!\n\n";
}else
cout << "You do not have a right triangle\n\n";

//Find a misssing side
}else if ((option == 's') || (option == 'S')) {
cout << "Do you want to find a hypotenuse or a leg ('h' or 'l')\n";
char opt;
cin >> opt;
//Find a missing leg
if (opt == 'h'){
cout << "Enter the value of the first leg: ";
float aleg;
cin >> aleg;
cout << "Enter the value of the second leg: ";
float bleg;
cin >> bleg;
result = sqrt (pow(aleg,2) + pow(bleg,2));
//Find a missing hypotenuse
}else if (opt == 'l'){
cout << "Enter the value of the known leg: ";
float kleg;
cin >> kleg;
cout << "Enter the value of the hypotenuse: ";
float khyp;
cin >> khyp;
result = sqrt (pow(khyp,2) - pow(kleg,2));
}else{
cout << "You entered a invalid command: ";
break;
}
}

//Clear, sets the result to 0
}else if (( oper_char == 'c') || (oper_char == 'C')) {
result = 0;

} else if (oper_char == '/') {
if (value == 0) {
cout << "Error: Divide by zero/n";
cout << " operation ignored/n";
} else
result /= value;
} else {
cout << "Unknown operator\n " << oper_char << '/n'; }


}
return (0);
}

sarin 08-04-2002 03:17 AM

Me too started learning cpp yesterday. But a simple suggestion. break at error line. I found it works. Also why don't you use switch in place of deeply nested if...else?
--Sarin

Mara 08-04-2002 03:49 AM

Small suggestion:
In programs you'd like to publish don't use 'cin >>' to int, float etc. The program will crash when entered value is not a number. Instead, read all numbers into char buffers, then convert them.

Scotty2435 08-04-2002 01:25 PM

how can i convert it from float or int to char

All the if loops are pretty messed up but that was the only way me and my friend knew how to do it. How could i implement switch loops.

Thanks

Eits0 08-04-2002 04:31 PM

Run it thru emacs debugger... that oughta give some data to work with...

BTW, ever heard of easy maintenance *looks suspiciously* your program looks straight said messy! At least I need to locate opening { with cats and dogs sometimes. :tisk:

Mara 08-06-2002 08:26 AM

Quote:

Originally posted by Scotty2435
how can i convert it from float or int to char
The following functions are useful:
atoi, atof, atol, strtol, strtoul, strtod.
Read their manual pages (they have them).

Quote:

All the if loops are pretty messed up but that was the only way me and my friend knew how to do it. How could i implement switch loops.
Code:

#include <iostream.h>
#include <cmath>
#include <math.h>
#include <string.h>
#include <ctype.h>
#include <stdlib.h>

float result; // the result of the calculations
char oper_char; // the user-specified operator
float value; // value specified after the operator
float memory; // Memory (wanted to use an array but couldn't get to work)

int main(void) {
        result = 0; // initialize the result
        memory = 0;
//Program Intro
        cout << "\n\nAndrew and Walton's Magnificent Calculator Program Now with MEMORY and INTEREST!!! \nPress 'h' for help menu\n\n";


// Loop forever (or until we hit the break statement)
        while (1) {


//Print the result
                cout << "Result: " << result << '\n';


                cout << "Enter operator and number: ";

                cin >> oper_char;


//Quit Statement

                switch(oper_char) {
                        case 'q':
                        case 'Q':
                                        return 0;

//Help Menu
                        case 'h': {
                                cout << "\nHelp:\n";
                                cout << "Commands:
                                        'Q' quit
                                        's0' for square root
                                        't0' for figuring tax amount (must enter rate)
                                        '^power' to figure exponents
                                        'c0' To clear all calculations and reset the result to '0'
                                        'p0' To set result to pi.
                                        'i0' To calculate interest
                                        'r0' To work with right triangles
                                        'm0' To copy the current result to memory
                                        'p0' To display the stored number" ;
                                cout << "\n\nPress 'r' to return to program: ";
                                char tmp_char;
                                cin >> tmp_char;
                                if ((tmp_char == 'r')) {
                                        continue;
                                }
                                break;
                        }
                        case '+': {
                                cin >> value;
                                result += value;
                                break;
                        }
                        case '-':        {
                                cin>>value;
                                result -= value;
                                break;
                        }

//Store Something in Memory

                        case 'm': {
                                memory = result;
                                break;
                        }

//Retrieve Memory

                        case 'p':  {
                                cout <<"Stored Number: " << memory << '\n';
                                break;
                        }

//Tangent doesn't work right needs help
                        case 'w': {
                                result = atan(result);
                                break;
                        }

//Interest Program
                        case 'i':
                        case 'I': {
                                cout << "Enter Principle amount: ";
                                float principle;
                                cin >> principle;
                                cout << "Enter Interest Rate (ex.7.65): ";
                                float rate;
                                cin >> rate;
                                cout << "Enter Number of Years: ";
                                float year;
                                cin >> year;
                                result = principle*pow(rate/100+1,year);
                                break;
                        }

                        case '*':  {
                                result *= value;
                                break;
                        }       
//Change result to pi
                        case 'P':  {
                                result = 3.1415926535;
                                break;
                        }
       
//Exponents
                        case '^': {
                                result = pow(result,value);
                                break;
                        }
       
//Tax Program
                        case 't': {
                                cout << "Enter Tax Rate (ex.6.54): ";
                                float tax;
                                cin >> tax;
                                if (isalpha(tax)){
                                        cout <<"You did not enter calculable numbers!!!\n\n";
                                        break;
                                /* Comment by Mara:
                                this does not work
                                */

                                }else{
                                        result = (tax/10)+1*result;
                                }
                                break;
                        }
//Square Roots
                        case 's':
                        case 'S': {
                                result = sqrt(result);
                                break;
                        }
       

//Clear, sets the result to 0
                        case 'c':
                        case  'C': {
                                result = 0;
                                break;
                        }
       
                        case '/': {
                                if (value == 0) {
                                        cout << "Error: Divide by zero/n";
                                        cout << " operation ignored/n";
                                } else
                                        result /= value;
                                break;
                        }
                        default: {
                                cout << "Unknown operator\n " << oper_char << '/n';
                                break;
                        }
                }
        }
        return 0;
}

It's not all, I got lost with one section, so it's not included.
As you can see it still looks quite messy. It's a good idea to create functions and divide your main().

rino.caldelli 03-05-2006 04:38 AM

If it ca help
int to string conversion itself is done like this:
Code:

/* fcvt example: scientific notations */
#include <stdio.h>
#include <stdlib.h>
#include<iostream>
using namespace std;

main ()
{
 int n = 5;
 char buffer[10]; /* long enough to hold your number + null */
 sprintf(buffer, "%i", n);
 cout<<buffer[0];
 
}



All times are GMT -5. The time now is 04:57 PM.