Joined: Sun May 25, 2008 5:34 pm Posts: 95 Has thanked: 2 time Have thanks: 1 time
Code:
/********************************************************************** * Calculator program. Runs in integer or floating point mode. * Commands are: * = <number> Enter <number> into the display. * <op> <number> Compute the operation: + - * / ^ * Note: The space after = or <op> is required. * i[nteger] Go to integer mode. * d[ouble] Go to double mode. * f[loat] Go to double mode. * q[uit] Exit * * There is a "display," and after each command is executed, the display * is printed out. Operation commands operate on the display as left * operand and the input number as the right operand, and return the * result to the display. Each command must be followed by a newline. * The operations are on integer or double type, depending on mode. * Changes into the current mode do nothing. Initially, the mode is * double and the display is zero, and the display is printed once * before the first command is read. Assumes that execution is * terminated with a 'q' command, so does not check EOF. **********************************************************************/ #include <iostream> #include <math.h> #include <ctype.h>
using namespace std;
main() { int idisp; // Integer mode display val char mode = 'd'; // Mode = 'd' or 'i' double ddisp = 0.0; // Double mode display val
// Input a command. We issue a prompt, skip leanding // blanks, read one non-blank which is our command, then // skip to the next digit, space, or lineend. char comd; // Command character. char ch; // Other input character. cout << '>'; if(cin >> comd) { // Skip to a digit, space, lineend, or EOF. while(cin.get(ch)) { if(isspace(ch)) break; if(isdigit(ch)) break; }
// If we reached a digit, pretend we never saw it. if(isdigit(ch)) cin.unget(); } else // If we reached EOF, pretend command is quit. comd = 'q';
/* discard up to a newline. */ while(ch != '\n') if(!cin.get(ch)) break; }
exit(0); }
This is a C++ program, but it includes a C header file, ctype.h. Ctype classifies characters; the isspace and isdigit functions come from this header.
Some new streams calls:
* The cin.get(ch) reads one chararacter into ch, but does not skip leading spaces. The cin >> ch construct does, so it won't read a space.
* The cin.unget() construct unreads the last character gotten from cin, so the next read from cin will fetch the same character again. (Generally, you can only go back one character.)