POV-Ray : Newsgroups : povray.off-topic : My first C++ program : My first C++ program Server Time
30 Sep 2024 13:19:27 EDT (-0400)
  My first C++ program  
From: Invisible
Date: 19 Sep 2008 08:03:59
Message: <48d3952f$1@news.povray.org>
(Yeah, I realise nobody else is going to care...)



#include <iostream>
#include <vector>
#include <string>

using namespace std;

bool StackCheck(vector<int> stack, int min)
{
   if (stack.size() >= min) return true;

   cout << "Stack underflow." << endl;
   return false;
}

void Add(vector<int>& stack)
{
   if (!StackCheck(stack, 2)) return;

   int x = stack.back(); stack.pop_back();
   int y = stack.back(); stack.pop_back();
   stack.push_back(x + y);
}

void Sub(vector<int>& stack)
{
   if (!StackCheck(stack, 2)) return;

   int x = stack.back(); stack.pop_back();
   int y = stack.back(); stack.pop_back();
   stack.push_back(x - y);
}

int main()
{
   cout << "Calc #01" << endl;

   vector<int> stack;
   string cmd;

   while (true)
   {
     for (int i=0; i<stack.size(); i++)
     cout << "[" << i << "]: " << stack[i] << endl;

     cout << "Calc> ";
     cin  >> cmd;

     if (cmd == "^") break;
     if (cmd == "+") {Add(stack); continue;}
     if (cmd == "-") {Sub(stack); continue;}
     stack.push_back(1);
   }

   cout << "Exit." << endl;
}



Almost unbelievably, even though this program is written in C++ and 
involves I/O, it seems to work correctly. I'm sure anybody who actually 
knows how C++ is supposed to work will have a good laugh at this, but I 
learned a few things by doing it.

The first mistake was passing the stack by value - which, obviously, 
fails miserably. The next thing I tried was returning the new stack to 
the caller, but that didn't work either. (Much like C, C++ compiler 
errors seem rather cryptic. Plus I'm running GCC under QEMU, so it takes 
about 60 seconds for each compiler run!)

At present, I haven't figured out how to convert a string to an integer 
yet, so this "calculator" is pretty much useless. I'm sure it'll be 
explained later in the tutorial. I also find myself constantly cursing 
that I have to write an entire 5 lines of (nearly identical) code for 
every arithmetic operation I want to implement and there's no way to 
abstract this. (I don't have copy & paste available!)

Also, there's an interesting glitch where the program won't continue if 
you enter a blank line - you must enter *something* or the program won't 
continue. Presumably this is just the defined behaviour of the >> 
operator...

Still, I have a program that reads user input without segfaulting. 
That's gotta be pretty impressive!

PS. Nano is a horrid, horrid text editor!


Post a reply to this message

Copyright 2003-2023 Persistence of Vision Raytracer Pty. Ltd.