LinuxQuestions.org
Review your favorite Linux distribution.
Go Back   LinuxQuestions.org > Forums > Non-*NIX Forums > Programming
User Name
Password
Programming This forum is for all programming questions.
The question does not have to be directly related to Linux and any language is fair game.

Notices


Reply
  Search this Thread
Old 08-03-2002, 06:14 PM   #1
Scotty2435
Member
 
Registered: Dec 2001
Location: Waco, Texas USA
Distribution: Redhat 7.1
Posts: 232

Rep: Reputation: 30
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
 
Old 08-03-2002, 06:27 PM   #2
Eits0
Member
 
Registered: May 2002
Location: Finland
Distribution: Mandrake 9.0
Posts: 188

Rep: Reputation: 30
try this one on problem point:
Code:
cin >> "n%";
else
 {
   cout << "Illegal operation! Forgive my sins, master!" << endl;
 }

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

Last edited by Eits0; 08-03-2002 at 06:31 PM.
 
Old 08-03-2002, 06:42 PM   #3
Mara
Moderator
 
Registered: Feb 2002
Location: Grenoble
Distribution: Debian
Posts: 9,696

Rep: Reputation: 232Reputation: 232Reputation: 232
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

Last edited by Mara; 08-03-2002 at 06:43 PM.
 
Old 08-03-2002, 09:21 PM   #4
Scotty2435
Member
 
Registered: Dec 2001
Location: Waco, Texas USA
Distribution: Redhat 7.1
Posts: 232

Original Poster
Rep: Reputation: 30
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);
}
 
Old 08-04-2002, 03:17 AM   #5
sarin
Member
 
Registered: May 2001
Location: India, Kerala, Thrissur
Distribution: FC 7-10
Posts: 354
Blog Entries: 2

Rep: Reputation: 34
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
 
Old 08-04-2002, 03:49 AM   #6
Mara
Moderator
 
Registered: Feb 2002
Location: Grenoble
Distribution: Debian
Posts: 9,696

Rep: Reputation: 232Reputation: 232Reputation: 232
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.
 
Old 08-04-2002, 01:25 PM   #7
Scotty2435
Member
 
Registered: Dec 2001
Location: Waco, Texas USA
Distribution: Redhat 7.1
Posts: 232

Original Poster
Rep: Reputation: 30
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
 
Old 08-04-2002, 04:31 PM   #8
Eits0
Member
 
Registered: May 2002
Location: Finland
Distribution: Mandrake 9.0
Posts: 188

Rep: Reputation: 30
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.

Last edited by Eits0; 08-04-2002 at 04:36 PM.
 
Old 08-06-2002, 08:26 AM   #9
Mara
Moderator
 
Registered: Feb 2002
Location: Grenoble
Distribution: Debian
Posts: 9,696

Rep: Reputation: 232Reputation: 232Reputation: 232
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().
 
Old 03-05-2006, 04:38 AM   #10
rino.caldelli
Member
 
Registered: Apr 2005
Location: perugia
Distribution: ubuntu
Posts: 181

Rep: Reputation: 31
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];
  
}
 
  


Reply


Thread Tools Search this Thread
Search this Thread:

Advanced Search

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

BB code is On
Smilies are On
[IMG] code is Off
HTML code is Off



Similar Threads
Thread Thread Starter Forum Replies Last Post
Newb question sicness Slackware 4 11-09-2005 03:40 AM
Newb Question Tsarok Fedora 5 07-14-2005 02:05 PM
Newb Question nFecTeD Linux - Newbie 1 06-07-2005 06:24 PM
A Newb Question pt. 2 gnr2k3 Linux - Newbie 3 08-30-2003 05:37 PM
A Newb Question gnr2k3 Linux - Newbie 1 08-30-2003 04:54 PM

LinuxQuestions.org > Forums > Non-*NIX Forums > Programming

All times are GMT -5. The time now is 12:52 PM.

Main Menu
Advertisement
My LQ
Write for LQ
LinuxQuestions.org is looking for people interested in writing Editorials, Articles, Reviews, and more. If you'd like to contribute content, let us know.
Main Menu
Syndicate
RSS1  Latest Threads
RSS1  LQ News
Twitter: @linuxquestions
Open Source Consulting | Domain Registration