Alex Edwards 321 Posting Shark
#include <iostream>
using namespace std;

int main ()

{

int twenties, tens, fives, singles, quarters, dimes, nickles, pennies;
double purchase, pay, rempay=0;
cout<< "please enter the purchase amount ";
cin>> purchase;
cout<< " please enter the payment amount ";
cin>> pay;
rempay = pay - purchase;
twenties = int(rempay/20);
rempay= rempay - 20;
tens= int(rempay/10);
rempay = rempay - 10;
fives= int(rempay/5);
rempay= rempay - 5;
singles = int(rempay / 1);
rempay = rempay - 1;

quarters = int(rempay / .25);

rempay = rempay - .25;
dimes = int(rempay / .10);
rempay = rempay - .10;
nickles = int(rempay / .05);
rempay= rempay - .05;
pennies= int(rempay / .01);



cout<< "twenties - " << twenties << '\n';
cout << "tens - " << tens << '\n';
cout <<" fives - " << fives << '\n';
cout << "singles - " << singles << '\n';


cout << "Quarters - " << quarters << '\n';
cout << "Dimes - " << dimes << '\n';
cout << "Nickels - " << nickles << '\n';
cout << "Pennies - " << pennies << '\n';



cin.ignore();
cin.get();
return 0;
}

Added cin.ignore() and cin.get() just before main finishes execution.

Even so, this is just a temporary problem. You can't rely on this if the user give improper input.

I'll pm you with what I have. Really sorry, thought you couldn't get an output going with the way the code was--

Note: You may want to consider using the modulus operator to …

Alex Edwards 321 Posting Shark

Yeah... actually now that I think about it, that sounds like it would work. I could do if(x=7, y=2){ type statements to represent towns, and increment/decrement x/y coordinates depending on which direction you pick.

I'm just not sure what the most efficient way to define the borders is, to make sure that the x/y coordinates won't get higher or lower than I want them to.

You don't need a 2D array of chars or anything else, just an array of structs and a starting-location for your character.

You'll probably also want to make a switch statement (or if statements) that handles the possible moves for the character.

typedef struct Location
{
      int x, y;
      Location(int col, int row) : x(col), y(row){}
};

Location Inn(4, 3), TrainingArea(2, 2), Gate(0, 4);
Alex Edwards 321 Posting Shark

this doesnt make any sense. what's any of this got to do with Windows API?

you've got an 8x8 matrix of single characters... what meaningful information can you have in such a thing?

you should make an 8x8 matrix of a structure that describes every important aspect of any board position.

True. You can have a struct that holds the x and y information of the board.

Unfortunately I wasn't given enough information at the start other than the fact that the original poster wanted a map in a text-based RPG and wanted the characters capable of moving around in the array without going out of the bounds.

My first suggestion was a restricted array (or class) that would not allow the user to go out of bounds.

I also assumed that the original poster wanted to visually understand what was going on and had enough C++ experience to use file I/O and represent the map as a set of characters.

Alex Edwards 321 Posting Shark

Oh I see. Well my original intent was to start with just a basic coordinate system, with no visible map displayed on the screen. As you move, it would display what square you moved to by outputting your coordinates. And the last feature I wanted was to have certain squares be represented by towns (and eventually dungeons), so for now I want to keep it simple until I've learned more in C++.

---|---|---|---
---|---|---|---
---|---|---|---
---|x | t |---

x <- you are here. Then you're given the option to move north, east or west.
t <- town here. Step on this square and you'll get to do town things like store/inn.

Then you just want to display the numbers and maybe display the numbers of the valid locations to move to next?

In that case I really don't think you need arrays or file i/o. You just need to have predefined coordinates for places.

Alex Edwards 321 Posting Shark
#include <iostream>
using namespace std;

template <class T>
class list
{
public:
	
	list();
	list(int);
	void insert(T);
	void remove();
	bool empty();
	void print();
	~list();

private:
	int size;
	T *thelist;
	int numinlist;
	int newsize;

};

template <class T> list<T>::list() : size(5), newsize(size)		//default
{
	T *thelist = new T[list<T>::size];
	numinlist=0;
}

template <class T> list<T>::list(int in_size) : size(in_size), newsize(size)		
{
	T *thelist = new T[in_size];
	numinlist=0;
}

template <class T> void list<T>::insert(T write)
{
    
	if(numinlist < list::size)
	{
		thelist[numinlist] = write;
		
		numinlist++;
		cout << "Numinlist is now" << "  " << numinlist << endl;
		cout << thelist[numinlist] << " " << numinlist << endl;
	}
	else
	{
        
		
		T *temp = new T[newsize];
		for (int i = 0; i < newsize; i++)
		{
				temp[i] = thelist[i];
		}
		     delete[] thelist;
		
		newsize++;
		T *thelist = new T[newsize];
        		
		for (int i = 0; i < (newsize - 1); i++)
		{
           thelist[i]= temp[i];
		}
		   delete [] temp;
	
		thelist[newsize - 1] = write;
		numinlist++;
		cout << "Numinlist is now" << "  " << numinlist << endl;	
	}
}


template <class T> void list<T>::remove()	//remove function
{
	if(numinlist > 0)
	{
		numinlist--;
		cout << "Numinlist is now" << "  " << numinlist << endl;
	}
	else
	{
		cout << "List is empty" << endl;
		exit(1);
	}
}

template <class T> bool list<T>::empty()	//detect empty function
{
	if(numinlist == 0)
	{
		cout << "List is empty" << endl;
		return true;
	}
	else
	{
		cout << "List is not empty" << endl;
		return false;
	}
}

template <class T> void …
Alex Edwards 321 Posting Shark

Why would you want to fill up the array with chars though?

You're trying to display your map on the screen correct?

Doing so with characters is your best bet unless you're using Windows API and you're forming an application.

You'll have to give me more details on your program - I'm thinking that you're making a text-based RPG to be seen in the Console screen, so the first thing that came to mind were pre-placed characters from a text file.

Alex Edwards 321 Posting Shark

Just 2, a chessboard with special squares (only bigger of course)

er, now that I think about it though, is it possible to have like dungeons or something that have their own specific map layouts?

Of course. It's your multi-dimension array, you can set it up any way you like.

You're going to want to do this the easy way... and when I mean the easy way I mean having your map already built in a .txt file then read the characters into a 2D char array...

#ifndef MAPXSIZE
#define MAPXSIZE 8
#endif
#ifndef MAPYSIZE
#define MAPYSIZE 8
#endif

typedef char MapArray[MAPXSIZE][MAPYSIZE] = {0};

MapArray firstMap, dungeon1Map, dungeon2Map; //... however many maps that you may need

//code to fill map with chars from .txt file
Alex Edwards 321 Posting Shark

You could create a class that handles the boundaries of your multi-dimension array.

My question is this -- are you planning on having only 2 dimensions for the map or 3 in the event that you want to do some kind of map-switch?

Alex Edwards 321 Posting Shark

Changed your constructor to initialize the size in this way--

template <class T> list<T>::list() : size(5)		//default
{
	T *thelist = new T[list::size];
	numinlist=0;
	newsize=5;
}

also changed your public static const variable to a private one--

private:
	int size;
	T *thelist;
	int numinlist;
	int newsize;

Then I made a change where you were doing constant damage to the heap, here--

newsize++;
		T *temp = new T[newsize];
		for (int i = 0; i < newsize; i++)
		{
				temp[i] = thelist[i];
                            //delete[] thelist //prior to edit
		}
		     delete[] thelist; //after edit

where you kept deleting the same address over and over in your for loop.

Same problem occurs here--

T *thelist = new T[newsize];
        		
		for (int i = 0; i < newsize; i++)
		{
                     thelist[i]= temp[i];
		}
		   delete [] temp; //after edit

Also, you may want to place the incremented newsize after the copying of the values into the temp pointer, don't do it right off the bat--

T *temp = new T[newsize];
		for (int i = 0; i < newsize; i++)
		{
				temp[i] = thelist[i];
		}
		     delete[] thelist;
		
		newsize++;
		T *thelist = new T[newsize];
        		
		for (int i = 0; i < newsize; i++)
		{
           thelist[i]= temp[i];
		}
		   delete [] temp;
Alex Edwards 321 Posting Shark

Division is repeated subtraction.
6/3 = 2.
3 can be subtracted from 6 twice, until you're left with zero. Which explains why dividing by 0 is infinity.
Multiplication is simply repeated addition.
Some old CPU's had no instructions for division and multiplication so people had to multiply/divide that way.

That's genius =)

I'll definitely have to remember that XD

Alex Edwards 321 Posting Shark

I found an interesting question on the internet...

An interviewer asked a programmer "How would you divide without using division or multiplication?" And the programmer came up with some weird bit shifting operation that did the division.

Now, I'd like to make a program that does something similar, since--

int a = 10;
a = a << 3

means 10 * (2^3)

and

a = 10
a = a >> 3

means 10 / (2^3)

--but I'd like to redefine the right operation (the 2 to the power of (arg) ) with an object from the bitset<N> class so that when a user does something like this..

bitset<4> bSet;
int a = 10;

for(int i = 0; i < 3; i++)
bSet.set(i); //should set the first 3 bits to 1, for 0111 or 2^2 + 2^1 + 2^0 = 7

a = a >> bSet;

... and perform 10 / 7 division.

I have an idea of how I should do this...

//somewhere in the operator overload command--

return arg1 / pow(2, log(arg2.to_ulong())/log(2));

--the question, though it may seem trivial, is how do I make this operator function overload the natural bitshifting operation for these operations? In short, where is the bitshifting defined exactly? I heard that << and >> respectively were cout and cin objects operators, but if they can be used for pure bitshifting then I …

Alex Edwards 321 Posting Shark

Does that mean I need a new unique global pointer for each object I want to keep global?

Not necessarily. You could make an object global without making it a pointer, but it seems that you don't want a predefined "reference variable" that calls a particular constructor upon declaration, and furthermore you don't want to have a default constructor then call the member function of that variable at a later time.

If you don't want to mess with pointers, I'd suggest using the "reference variable" technique, otherwise you may have to deal with double pointers, or possible even a container like the vector class that holds character objects.

For example...

#include <vector>
vector<Character> charList; //vector that can hold character objects, declared at global scope

//... code to fill the vector via push_back(Character c)

I'd suggest studying vectors and staying away from double pointers, or you'll end up with a headache.

I can tell you the code for using double pointers, but it would be obnoxiously messy.

Here's a link for the vector class -- http://www.cplusplus.com/reference/stl/vector/

Alex Edwards 321 Posting Shark

Thanks for the help I was able to get this to work. Is there a list on the Sun site that shows all the different types of exceptions?

I would look up (in google) either--

java class Exception 6.0

or

java throwable 6.0

--and I say 6.0 because I assume you want some of the latest information.

From there you can study all of the possible Exceptions. To my knowledge, there should be over 30 of them.

Alex Edwards 321 Posting Shark

If I were to do that, how would I call my member functions with that object?

Also, I thought I didn't want to have to have the program call a member function to set the stats for my object. Maybe I misinterpreted what I was reading, but that seemed to be what the author was saying.

You would use pointer notation to call member functions, i.e...

cPtr->doSomething(); /*calling the method doSomething in the Character class the pointer is pointing to*/

--and as stated before, you did not call the constructor of the object until the case/break. Therefore your program wasn't directly calling a member function, but rather instantiating said object when "new" was declared.

Alex Edwards 321 Posting Shark

Thank you Alex, as usual, you are the soul of courtesy, my apologies if you took any offense to the second comment.

No offense taken. My response wasn't fairly directed so the reply is understandable.

Alex Edwards 321 Posting Shark

If you are referring to the first question, I know it compiles, but I also know that doesn't necessarily mean it's right, was just looking for a confirmation that it's correct for a template, or no, you're missing stuff.

It's correct because you've generalized your list. That's one of the primary functions of templates - to make a general case for all valid objects/types.

Instead of only taking ints, it now takes anything that is a valid T parameter.

There are other reasons for templates, such as meta-programming and (supposedly) allowing a potential "bridge" for inheritance issues but from what I've heard the bridging isn't really a serious performance bump.

If you want an example of template meta-programming, consider the following code--

#include <cstdlib>
#include <iostream>

using namespace std;

class Fibonacci{
     public:
            template<int N>
            inline unsigned __int64 series(){   
                return (this->series<N - 1>() + (this->series<N - 2>()));
            }
};

template<>
inline unsigned __int64 Fibonacci::series<1>(){
    return 1;
};

template<>
inline unsigned __int64 Fibonacci::series<0>(){
    return 0;
};

int main(int argc, char *argv[]){
    const int n = 6;
    Fibonacci fib;
    cout << fib.series<n>() << endl; //prints out the nth result of the Fibonacci series
    cin.get();
    return 0;
}
henpecked1 commented: Alex was, as usual very helpful and very kind in his replies +1
Alex Edwards 321 Posting Shark
------ Build started: Project: AngleFinder, Configuration: Debug Win32 ------
Compiling...
SteveAngle.cpp
.\SteveAngle.cpp(85) : error C2296: '/' : illegal, left operand has type 'long double (__cdecl *)(const float)'
.\SteveAngle.cpp(88) : error C2297: '/' : illegal, right operand has type 'long double (__cdecl *)(const float)'
.\SteveAngle.cpp(119) : error C2296: '/' : illegal, left operand has type 'long double (__cdecl *)(const float)'
.\SteveAngle.cpp(122) : error C2297: '/' : illegal, right operand has type 'long double (__cdecl *)(const float)'
.\SteveAngle.cpp(151) : error C2297: '/' : illegal, right operand has type 'long double (__cdecl *)(const float)'
Build log was saved at "file://e:\Steve'sDocs\Visual Studio 2008\Projects\AngleFinder\AngleFinder\Debug\BuildLog.htm"
AngleFinder - 5 error(s), 0 warning(s)
========== Build: 0 succeeded, 1 failed, 0 up-to-date, 0 skipped ==========

Are you trying to divide using a divide char?

Or are you trying to divide by a floating-point value?

Alex Edwards 321 Posting Shark

Is my question really that dumb that I get nearly 30 views and no replies...lol

You answered your own question.

Alex Edwards 321 Posting Shark

I'm fairly certain that in order to import c++ code into another language (like Java for example), you will need a dynamic link library in order for the process to be possible.

There are far more reasons for .dll files but I don't know of them yet myself. In fact, the main reason I started practicing c++ a little over a month ago was to learn it for the native methods I was learning from Java.

Alex Edwards 321 Posting Shark

Why not make a pointer to Character objects in global scope and then, based on the class the user suggest, instantiate said stats?

example...

//in global scope

Character *cPtr; //Notice your constructor isn't called yet
//when user inputs a char..
    char classChoice;
    cin>> classChoice;


    switch(classChoice)
    {
         case 'W':
         case 'w':
                       cPtr = new Character(/*Warrior stats here*/);
                       break;
         case 'M':
         case 'm':
                       cPtr = new Character(/*Mage stats here*/);
                       break;
          default:
                       cout << "Improper selection" << endl;
                       break;

    }
Alex Edwards 321 Posting Shark

Oh I see,
multiply the polynomials and store the newly valued exp and coef in a new map?
Ill give it a shot and let you know. Thanks!


As for the division, I am not required to do it.

Good, because that would involve Regex or factoring the regular polynomial into a general polynomial for both lines and finding a matching factored polynomial from both lines.

What happens if they're not factorable is beyond me - you'd have to literally store the entire expression in one node, or inform the user that they cannot be divided generally.

Alex Edwards 321 Posting Shark

I have to add/subtract/multiply 2 lines of polynominals

say line 1 is
x^2+3x+3
line 2 is
3x^2+4x+4

adding would be
4x^2+7x+7
and so on...

I have map<int, int>
exp as key and coef as data

I gotten the adding and subtracting but is the multiplying is giving me trouble because I have to modify the exp which is the key.

For Multiplication...

What you could do is make another map a receiver map.

You know how many nodes you'll need because through multiplication you would need Line1 coefficients * Line2 coefficients, so you'll need 9 slots to store the new polynomial.

From there all you would need to do is multiply Node1 from Map1 with the All 3 nodes from Map2 and store the result nodes in the receiver map. Rinse and repeat for Node2 and Node3 from Map1.

If you run into the same exponent then simply do addition. You'll have at most Line1 * Line2 nodes, but its possible that if a key collision occurs then you should replace the old value with the sum of the new value and the old value - the key should be the same.

As for division im still thinking about it. Thanks for being a bit more thorough with the information.

Alex Edwards 321 Posting Shark

Yeah is the first one.

x^2 + 9x - 10

c = 1, exp = 2
c = 9, exp = 1
c = 10, exp = 0

Oh then it looks like you have the right approach.

Are you then replacing the x's with a said-value and then doing the math?

And the type of equations you're having issues with are --

x^2 * 9x / 10

--correct?

Alex Edwards 321 Posting Shark

Does it still involve using maps? because I have to use maps.

Yes.

I was thinking of something along the lines of--

Map<int, vector<int> >

--where you store the values in the map in such a way that if you ever add a key/value to the map that is the same, you can overwrite the old key with the new key and old value in the same vector as the new value..

Also, what kind of expressions are you doing? Something along the lines of--

x^2 + 9x - 10

-- ?

Or is it something like--

Keys (exponents) -> 2, 3, 4
Values (coefficients) -> 1, 10, 2

1^2 (+, -, /, *) 10^3 (+, -, /, *) 2^4

I need some more information

Alex Edwards 321 Posting Shark

I was doing well in this project until I was trying to do the math problem on the third class.
The project is, we are supposed to create a base class of circle and create 2 derived classes
The first is sector derived from circle then the segment is derived from sector. It ran ok until the math in the sector was outputing junk. Can you show me why the values from circle and segment is not getting transferred despite calling it? NEED THE CODE ...
here it is!

First of call, use code tags please...

code=c++

/code

...put your code between both statements but add brackets to them.

Secondly I tried checking your program - guess what, it doesn't compile. There are quite a few issues.

The first was the fact that you were calling the super constructor that didn't exist. I changed that, then ran into other problems in main, as well as the fact that your class didn't overload the std::ostream operator.

There were just too many problems, as well as a missing header file. You'll have to supply all of the code (or an ample amount of it) for us to steer you in the right direction to solving the problem.

Alex Edwards 321 Posting Shark

I am using Maps from the STL to insert a polynomial.
The Key is the exponent and the data is the coefficent.

Basically I want to add/subtract and multiply them.

I have the addition/subtraction down but when it comes to multiplying
I have to add the exponents and multiply the coefficients.


I can't alter the exponent cause is the key.
Is there an alternate approach? Can the key be modified?

Is it required for you to use an exponent as a key?

I can think of 2 other ways of doing it if its not required.

Alex Edwards 321 Posting Shark

Point made: it's obfuscatory and should only be used in the archaic systems, from whence it came, that lack the appropriate machine commands and/or a supporting assembly code library.

I laughed so hard when I read this...

winner

Dave Sinkula commented: I actually have encountered it in the wild for this very reason, as I imagine AD has. +14
Alex Edwards 321 Posting Shark

What I posted is also the method used to convert a string of digits to an integer if you don't want to use a standard C or C++ convertion function.

Here's aother way: int c = (a << 3) + (a << 1) + b;

Edit: Wrong on my part, sorry.

Edit2: Actually... I think I got it.

a << 3 is the same as a * (2 ^ 3)
a >> 3 is the same as a / (2 ^ 3)

Correct me if I'm wrong on this.

Alex Edwards 321 Posting Shark

Actually the subject that I am doing the thesis has nothing to do with programming or software. The subject is called something like: Environmental Protection. And the application will have to be a system that monitors the materials that Industries use and the wastes that they produce. Since one industry's waste could be used by another industry for material, there should be a network with all the industries and I will have to deterine which one needs what from whom.
It is easy to be done in java, but since the lab that the professor runs consists mostly of chemists, the only thing they know is VB and access.
So he wants it to be done in VB in order for the application to run with the other programs they have.
Besides I shouldn't have a problem learning a new language. I just wanted a good book to get me started, based on my java background.

From what I saw, VB is fairly adjacent to Java, except that it is easier.

My friend took a VB class and from what I noticed (with less Java experience than you) is that a lot of what they do deals with manipulating Windows. A lot of the code looks like Java "inner classes" with commands (sort of like built-in action listeners / executors), etc.

The only thing you'll really have to know is the syntax and of course a library to use the functions. I'd suggest looking up …

Alex Edwards 321 Posting Shark

>I think you're right on that one.
It depends on what you mean by "char". If you're talking about the char data type, it's always equivalent to one byte in C++, for whatever the definition of a byte is. I think Vernon is assuming that a byte always equates to an 8-bit entity, which is not true.

On the other hand, if you're talking about a logical character, such as with Unicode, then a single character could very well be represented by more than one octet[1].

[1] Which is the correct term for an 8-bit entity.

Yeah I was referring to the difference between Unicode and ANSI chars ( wchar_t and char).

Alex Edwards 321 Posting Shark

>I tried to be as constant as possible... I got the following errors--
When I move around code, I do it for a reason. In this case, I moved the definition of mStruct outside of main because extern variables can't be initialized there. Oddly enough, your error says just that. :icon_rolleyes:

Thanks Narue =)

I admit I didn't pay enough attention when I saw the reply. My own fault.

Alex Edwards 321 Posting Shark

Give this a try. Basically you have four integers from 0 to If it's not, this won't work. I think (not 100% positive) that some compilers set aside more than one byte for a char.

I think you're right on that one. I read something interesting about why chars have different types and that some Operating Systems (if not compilers) will interpret chars differently.

Alex Edwards 321 Posting Shark
template<>
class ShowValues<1> { //specialized case for when N = 1
public:
    static inline void show()
    {
        cout << "Reached 1" << endl;    
    }
};

struct MyStruct
{
       public:
              
            int x, y;
       
            MyStruct(int first=0, int second=0): x(first), y(second){};
            const int getX()const{return x;};
            const int getY()const{return y;};
};


typedef class RestrictedTemplateClass
{
      public:
      
      template<const MyStruct &B> //template that has a restricted parameter - must be a MyStruct reference or greater
      const static void displayParameters()
      {
           cout << B.getX() << ", " << B.getY() << endl;
      };
}RTC;

int main(int argc, char *argv[])
{
    
    extern const MyStruct mStruct ( 1, 2 );
    
    RTC::displayParameters<mStruct>();
    
  //  ShowValues<10>::show();
    cin.get();
    return 0;
};

I tried to be as constant as possible... I got the following errors--

... In function `int main(int, char**)': 
58 ...`mStruct' has both `extern' and initializer
60 ... `mStruct' cannot appear in a constant-expression
60 ... template argument 1 is invalid
60 ... no matching function for call to `RestrictedTemplateClass::displayParameters()' 
 ... [Build Error]  [testingTemplateRecursion.o] Error 1

This is my first time dealing with extern. I've seen it a few times but I never practiced using it.

Alex Edwards 321 Posting Shark

You should be able to step through the string pushing the tokens onto the stack (with appropriate operand and operator validation) and when you encounter a closing paren, pop from the stack back to the last open paren, evaluate that result, and then push that result value onto the stack and proceed forward parsing.

That sounds ideal. Thanks a million.

Alex Edwards 321 Posting Shark
#include <cstdlib>
#include <iostream>



/**
Test Class for learning template-metaprogramming
*/

using namespace std;

template<int N> //General case for a number
class ShowValues {
public:
    static inline void show()
    {   
        cout << "Start: " << N << endl;
        ShowValues< (N > 1) ? (N - 1): 1>::show();
        cout << "Finish: " << N << endl;
    }
};

template<>
class ShowValues<1> { //specialized case for when N = 1
public:
    static inline void show()
    {
        cout << "Reached 1" << endl;    
    }
};

struct MyStruct
{
       public:
              
            int x, y;
       
            MyStruct(int first=0, int second=0): x(first), y(second){};
            int getX(){return x;};
            int getY(){return y;};
};


typedef class RestrictedTemplateClass
{
      public:
      
      template<MyStruct &B> //template that has a restricted parameter - must be a MyStruct reference or greater
      static void displayParameters()
      {
           cout << B.getX() << ", " << B.getY() << endl;
      };
}RTC;

int main(int argc, char *argv[])
{
    
    const MyStruct *const mStruct = new MyStruct (1, 2);
    
  //  RTC::displayParameters<mStruct*>(); //apparantly this doesnt work?
    
  //  ShowValues<10>::show();
    cin.get();
    return 0;
};

Why is it that I cannot call th method in RTC::displayParameters() with the template-argument mStruct* when it is clearly a constant reference?

The errors I receive when I uncomment the code are--

... In function `int main(int, char**)': 
60 ... `mStruct' cannot appear in a constant-expression 
60 ... template argument 1 is invalid 
60 ... no matching function for call to `RestrictedTemplateClass::displayParameters()' 
... [Build Error]  [testingTemplateRecursion.o] Error 1
Alex Edwards 321 Posting Shark

I was thinking of resorting to a stack long before I considered Regex.

I thought that it would be best for me to try Regex first, since there will be times I will have to account for a situation like--

"5 - ( 1 + cos(x + 2))"

--where I would want to retain a value without removing its parenthesis which leads to more complicated "searching" issues within the String.

I now see why it is not a mystery for programs to be expensive when evaluating string-based equations.

Alex Edwards 321 Posting Shark

Hi i just wanted to ask whether we cud use #include<string> and declare a data type called 'string' eg. string ch;? and where is "using namespace std" used?

The Standard Template Directory (or Definitions... or Defined types...) is a namespace with defined C and C++ types/functions/objects.

Without the "using namespace std" you would have to make calls to the std's objects in this way--

//without the using namespace std

std::cout << "Making a call to the cout and endl objects from namespace std" << std::endl;

--and about your first question, I'm not sure if I'm answering your question correctly when I say this, but yes you can declare a variable of type String in that way... however I'd suggest that you use the call to the constructor of the string object in this way--

#include <string>

string ch = "MyString";
Alex Edwards 321 Posting Shark
Alex Edwards 321 Posting Shark

I'm not sure if you've already implemented this class or not, but it may help you--

[url]http://www.cppreference.com/cppbitset/all.html[/url]

Alex Edwards 321 Posting Shark

Ok thanks I think I understand my previous question but another question are the values "3" and "4" or "5" and "6" stored in any specific variable?

Like if I wanted to show the "3" and "4" can I write a line

cout <<specificvariable;

what would that specificvariable be?

If you want to display the individual variables, you will have to understand that calling rect.x or rectb.x and rect.y and rectb.y are illegal calls since classes are initialized with private member variables until you provide public access members/functions.

If you want to get a specific variable, you'll need to provide a public "getter," like this--

class CRectangle {
    int x, y;
  public:
    void set_values (int,int);
    int area () {return (x*y);}
    int getX(){return x;};
    int getY(){return y;};
};

Now for rext and rectb you can call getX() and getY() with cout to display their respective x's and y's--

cout << rect.getX() << ", " << rect.getY() << endl;
cout << rectb.getX() << ", " << rectb.getY() << endl;
Alex Edwards 321 Posting Shark
CRectangle rect, rectb;
  rect.set_values (3,4);
  rectb.set_values (5,6);
  cout << "rect area: " << rect.area() << endl;
  cout << "rectb area: " << rectb.area() << endl;

rect and rectb are 2 different variables that are of the same class-type.

to make the code more understandable it might be better for you to do something like this--

CRectangle rect; // a CRectangle reference-variable named rect
  CRectangle rectb; // a CRectangle reference-variable named rectb
  rect.set_values (3,4);
  rectb.set_values (5,6);
  cout << "rect area: " << rect.area() << endl;
  cout << "rectb area: " << rectb.area() << endl;
Alex Edwards 321 Posting Shark
MySuperType mytype = null;
if (sub_type) {
     mytype = new MySubType (); //should be ok
     mytype.setD(4);
     mytype.setE(5);
} else {
     mytype = new MySuperType (); //Most likely a compiler error
}

mytype.setA(1);
mytype.setB(2);
mytype.setC(3);

When you do something like--

Object obj = new String("Upcasted!");

--it is called upcasting. String is a derived form of an Object, so this code is valid. However the reverse shouldn't be true--

String str = new Object() // WRONG!

--Because Object can contain data of any derived type, like we have shown above. It may be possible that the data stored in the Object has nothing to do with the data in the String class. Now if you do this--

String str = (String)new Object(); //Not quite right

--you're downcasting the object from its current type to a type it might consist data of. Since it's a new Object it is impossible to have data of a String object since the term "data" really depends on the creation of the object (during the constructor call).

When you create a String for example, there's a constructor call to String's super constructor - Object. Therefore String has data of Object, and when the Super constructor finishes execution, Strings constructor finishes execution as well so it additional contains data of a String.

This means that String can be supercast into an Object type (for whatever purpose you need to supercast), but an Object cannot always be downcast into a String (because it's …

Alex Edwards 321 Posting Shark

thanks... u can edit ur quote as well if u would like. :)

I'll keep it as-is for the record XP

Whats important is that you made the change =)

Alex Edwards 321 Posting Shark

haha Narue you're a funny guy, i'm not so bad at picking out the experts and arrogant individuals either. Thanks anyways for the link.

Better edit this quick... Narue is a woman =P

Alex Edwards 321 Posting Shark

If you start with say int tower_dmg_original[5][3] = {{1,2,3},{4,5,6},{7,8,9},{10,11,12},{13,14,15}}; Then later on, you could do this

int tower_dmg[5][3];
for ( int r = 0 ; r < 5 ; r++ ) {
  for ( int c = 0 ; c < 3 ; c++ ) {
    tower_dmg[r][c] = tower_dmg_original[r][c];
  }
}

Since you have 5 separate arrays all of the same size, make it a function.

Or better yet, you could do something like...

typedef int tower[5][3] = {{1,2,3},{4,5,6},{7,8,9},{10,11,12},{13,14,15}};

tower tower_dmg_original, tower_spd, tower_eff, tower_efc, tower_cst;

Now all of your towers will be initialized.

Alex Edwards 321 Posting Shark

I'd like to apologize for my previous post- I meant to place the array subscript next to the variable name and not the type.

Switching back and forth between C++ and Java today isn't a good thing @_@

//Somewhere under the header, near the namespace declaration...

char guessedChars[27] = {0}; //correct syntax
Alex Edwards 321 Posting Shark
#include <iostream>
#include <fstream>
#include <string>
#include <iomanip>
#include <time.h>

using namespace std;

void Hangman();
void LeftArm();
void Head();
void RightArm();
void Body();
void LeftLeg();
void Gallows(int count);
void DisplayAWord(string guessword);
void revealword(char letter, int position,string fileword, string guessword);
void secret(string fileword);
void hidden (string fileword);
char Question ();

int main()
{

srand(time(NULL));
int x = rand()%10 +1;
int count = 0;
int position;
char letter;
ifstream words;
string guessword, fileword;



words.open("words.txt");
do{
words>> fileword;}
while ( --x >= 0 );




secret(fileword);


while (guessword != fileword && count < 6){

letter = Question();
position = fileword.find(letter);

if (position > fileword.length()){
cout<<"There is no "<<letter<< "\n";
count++;
Gallows(count);}
else {
cout<< letter << " is in the "<<position<<"th place\n";
string guessword;
revealword(letter, position, fileword, guessword);
DisplayAWord(guessword);
}

}

if (count >= 6)
cout<<"Gameover man!\n";
cout<<"The word was "<<fileword<< ".\n";
false;


return 0;
}
void LeftArm()
{
cout << setw(8) <<"____" << endl;
cout << setw(4) <<"|" << setw (5) << "}" << endl;
cout << setw(4) <<"|" << setw(4) << "\\" << endl;
cout << setw(4) <<"|" << endl;
cout << setw(4) <<"|" << endl;
cout <<"___|________" << endl;
}
void Head()
{
cout << setw(8) <<"____" << endl;
cout << setw(4) <<"|" << setw (5) << "}" << endl;
cout << setw(4) <<"|" << setw(5) << "\\0" << endl;
cout << setw(4) <<"|" << endl;
cout << setw(4) <<"|" << endl;
cout <<"___|________" << endl;
}
void RightArm()
{
cout << setw(8) <<"____" << endl;
cout << setw(4) <<"|" …
Alex Edwards 321 Posting Shark

>So your telling me what is being displayed on my windows
>screen is the output of a combination a C++ program?
I'm telling you that the Windows operating system is written in a combination of C and C++. Most of the programs you run are as well.

>but howwwwwwwwwwwwwwwwwww :O
Not to be rude or anything, but if you're as new to programming as it seems, you won't get it even if we told you. There's a lot of prerequisite knowledge that comes with understanding how non-trivial programs are written. As you learn more about programming and C++, you'll gradually come to an answer.

Even after 3 quarters of Java and researching c++ extensively as well as coding... I am at the point where I need to learn the UML and at the moment it seems like I'm mixing beans with pickles..

I totally understand what you mean by that bolded comment. When I started looking into UML's I realized that projects are just ideas from one person... they're thought out not just before the design but during the design and even after the design.

Its no wonder that new versions of programs come out fairly quickly.

Alex Edwards 321 Posting Shark

What in the world does line 20 do?

19: SimpleCat::SimpleCat(int age, int weight):
20: itsAge(age), itsWeight(weight)
{}

The bolded part denotes an initialization done during the Constructor call. itsAge is set to age and itsWeight is set to weight when the constructor is called (sort-of like a pre-initialization). I suppose it reduces code-clutter in the Constructor, but I'm sure there's more to it than that.

Alex Edwards 321 Posting Shark

This isn't exactly a thread about a particular question, but a thread that may help people with memory dynamically allocated/deallocated during runtime. The below example goes over pointers in multiple dimensions--

#include <cstdlib>
#include <iostream>
/**
This program can be used to determine whether pointers are deleted
or not by the end of the program.
This will be a good tool to determine how to delete objects.
*/
using namespace std;

class MemoryManager{
      
      private:
             int index;
             static int x;
             
      public:
             MemoryManager(){
                  index = x++;
                  cout << "Creating class: " << index << endl;          
             }
             ~MemoryManager(){
                 cout << "Deleting value. Now " << --x;
                 cout << " objects remain."<< endl;
             }
             int getIndex(){return index;}
             
             static void showRemaining(){       
                   cout << "The total amount of existing objects are: ";
                   cout << x << endl;
             }
};

int MemoryManager::x = 0;

/*
 *Below are several cases I made up on my own for multi-dimensional pointers.
 *A fair warning: DO NOT USE ALL CASES AT ONCE! Doing so WILL cause damange to
 *the heap! Be very careful with this program.
 **/
int main(int argc, char *argv[])
{
        //To be commented out for the below cases
       /*
       MemoryManager **mm = new MemoryManager*[5];
    
       for(int i = 0; i < 5; i++)
       {
            mm[i] = new MemoryManager[2];
       }*/
    
       //Solution
       //case 1, apparantly the correct case
       /*
       {
         for(int i = 0; i < 5; i++)
         {
               delete[] mm[i]; //[rows] of the pointer mm
               //can be thought of as deleting the last array of values at the [ith] …