Intrade 33 Junior Poster

*sigh* I didn't want to bother posting this because I'll probably get flamed, but maybe you can make use of it--

/**
 * Numerics.h
 */
#ifndef NUMERICS
#define NUMERICS

#include <sstream>
#include <string>
#include <iomanip>

using namespace std;


/**
 * Convenience class for enabling easy
 * conversions between strings and primitive types.
 *
 * This class is not meant to support non-primitive types,
 * but it should if target class Type has istream and ostream
 * operators overloaded.
 */
namespace Numerics{

	template<class T> class Numerical;

	template<>
	class Numerical<float>{
	
		private:
			float number;
			int precision;
			static const int PRECISION_LIMIT = 60;

		public:
			/**
			 * Constructs a Numerical<float> based on a float
			 */
			Numerical(float value = 0) : number(value), precision(8){
				(*this)(getString());
			}

			/**
			 * Attempts to construct a Numerical<float> based on the string input
			 */
			Numerical(const string& arg){
				(*this)(arg);
			}

			/**
			 * Sets the precision setting. The setting will be adjusted to fit within 1-to-PRECISION_LIMIT
			 * which is 60.
			 */
			Numerical<float>& setPrecision(int pv){

				precision = (pv >= 1) ? ( (pv <= PRECISION_LIMIT) ? pv : PRECISION_LIMIT) : 1;

				(*this)( getString() );
				return *this;
			}

			/**
			 * Returns the current precision setting
			 */
			int getCurrentPrecision(){return precision;}

			/**
			 * Attempts to assign the argument value to the value
			 * of this Object's type.
			 * If the value is invalid, nothing happens.
			 */
			string operator()(const string& arg){
				stringstream ss (stringstream::in | stringstream::out);
				try{
					ss << setprecision(precision);
					ss << arg;
					ss >> number;
				}catch(...){
					throw string("Invalid String!");
				}
				return ss.str();
			}

			/**
			 * Attempts to …
Intrade 33 Junior Poster

Just noticed this, but you're comparing the computer(s) characters to integers --

// computer choice
	if (computer == 0)
		cout << "Computer: R" << endl;
	else if (computer == 1)
		cout << "Computer: P" << endl;
	else if (computer == 2)
		cout << "Computer: S" << endl;

-- that would be fine if you were using the appropriate ASCII char masks to compare against 'R', 'P' and 'S' but you are not. You should change the numbers to the appropriate character.

In addition, I still do not understand why you want to call humanChoice twice (once before printScore and then after). You can use cin to a varible so you aren't printing weird data to the screen... it's not really intuitive to the action you are performing.

Intrade 33 Junior Poster

What exactly do you mean by updating? As in appending some information, incrementing the value of the char or how many times it is accessed? What exactly do you mean?

And please use code-tags for your code-

[CODE=c++] //...code  [/CODE] 
Intrade 33 Junior Poster

Just call printScore without a condition or the computer choice since you're performing the game-choices in printScore anyways.

//...

while (true)
{
    cout << "Press Q if you want to quit, or any other key to continue" << endl;
    char theDecision;
    cin >> theDecision;
    if (theDecision == 'Q' || theDecision == 'q') break;
       printScore();

//...
void printScore()
{
	char human;
	char computer;
        cout << "Getting the human choice and computer choice: " << endl;
	human = humanChoice();
	computer = computerChoice();

	if (human == 'R' || human == 'r')
		cout << "\tHuman: R" << endl;
	else if(human == 'S' || human == 's')
		cout << "\tHuman: S" << endl;
	else if(human == 'P' || human == 'p')
		cout << "\tHuman: P" << endl;
        else cout << "ERROR! Invalid Human Choice!" << endl;

	if (computer == 0)
		cout << "\tComputer: R" << endl;
	else if (computer == 1)
		cout << "\tComputer: P" << endl;
	else if (computer == 2)
		cout << "\tComputer: S" << endl;
}

-- It's also good to add output between function calls to see which function you're stepping into or which line of instruction is reached.

I can't really see where the error is unless it's a logic error? Can you post all of your new code for us to see (i.e. changes to humanChoice or computerChoice)?

Intrade 33 Junior Poster

Ancient Dragon, you always amaze me with your code.

How do I hash this out on paper so I'm not stuck wondering how to format my output? How should I conceptualize the left/right/internal modifiers being used with setw?

http://www.cplusplus.com/reference/iostream/manipulators/left/

From the code given, is it safe to assume that fill characters are appended to "the end" of the strings and then the beginning of the fill characters to the first set of numbers with a fill-capacity of 19? Or do the right fill characters start from the numbers and overlap/connect with the left fill characters?

Sorry if that question was long-winded. I just want to see if my understanding is correct here. So far I think it's something like the following?

In this example, 'W stands for fill character

End setw(8) from right
                                  V
                         End setw(11) from left
                               V
 J  a  n  u  a  r  y 'W 'W 'W 'W 'W 'W 'W 'W 'W 'W 'W  1
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
 F  e  b  r  u  a  r  y 'W 'W 'W 'W 'W 'W 'W 'W 'W 'W  2
[ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ][ ]
Intrade 33 Junior Poster

It seems that you already had the functions getLength() and getWidth() defined in your class. You can actually delete the duplicate functions defined outside of class scope, so these functions you should completely remove from your code--

float Rectangle::getWidth()
{
	return W;//Is this right?
}

float Rectangle::getLength()
{
	return L;
}

-- because your class already has them defined and double-defining is illegal.

My apologies for not catching this the first time. I immediately assumed you followed the header/source file format for classes within one file. What I mean is I assumed this--

// file data.h

struct data{

   void p();

}
// file data.cpp

#include <iostream>

using std::cout;
using std::endl;

void data::p(){
    
   cout << "data:p()" << endl;
}

-where the class functions are not yet defined until later in the same file or in a different file. That is the usual format for classes, but you don't really have to follow it.

Alright, another thing. About rectangles. What is needed to define the perimeter and area of the rectangle? A rectangle is nothing more than a shape that is surrounded with 4 lines enclosing the shape with four 90 degree angles and each set of parallel sides have the same length as its parallel side (but it isn't restricted to not being the same length of its perpendicular side, so a rectangle can be a square... but a square cant be a rectangle). You only need 1 length and 1 width to determine the perimeter …

Ancient Dragon commented: ++ for good advice +34
Intrade 33 Junior Poster

You forgot to prefix the functions with your classname... right now the compiler sees getWidth() and getLength() as functions declared/defined outside of your class that are independant of your class, so the variables W and L are searched for in global scope and not found--

//...

// prefix getWidth with classname
float getWidth()
{
	return W;//Is this right?
}

//...
// prefix getLength with class name
float getLength()
{
	return L;
}

//...

-- And your function --

void Rectangle::get(float L, float W)
{



}

-- wasn't declared in your class. This is easily remedied by declaring it in your class--

class Rectangle{

 public:
   //...
   void get(float L, float W);
   //...

}

--

// You only have on colon specified between Rectangle and perimeter versus ::
double Rectangle:perimeter(float L, float W)

-- check the comment above area --

class Rectangle // Class Rectangle
{
public:
	Rectangle(float L, float W); // Constructor
	float getLength(){return length;}
	void setLength(float L);
	float getWidth(){return width;}
	void setWidth(float W);
	double perimeter(void){return (length*2 + width*2);} // Perimeter function

        // notice area no longer accepts void but instead desired parameter
	double area(float length, float width) {return (length*width);} // Area funcion

-- Be sure to spell out Rectangle exactly the way your class has the name spelled out --

int main() // main() I'm sure something is wrong here. 
// I understand the main function, but when I use classes I get confused...
{
Rectangle MyRectangle;

-- if you want to shorthand spelling …

Intrade 33 Junior Poster

Just for the record--

const char* x = "";

-- is valid because "" means a 0 length string. Anytime you use the quotes versus apostrophes you're dealing with const char* type.

char y = ' ';

-- This uses apostrophes to make a space-char and assign it to y.

Take these two things into account and relook at your code. You'll realize that--

char humanChoice()
{
	char choice = ""; // choice is type char but you're trying to assign it a string
	
	while(true)
	{
		cout << "Choose(Rock,Paper,Scissors,or Quit): ";
		cin >> choice;
		cin.ignore(1000, 10);

                // char versus const char* type not defined
                // where "Q" and "q" is the const char* and choice is the char
		if (choice == "Q" || "q") break;

                // same cases here...
		if (choice == "R" || choice == "r") break;
		if (choice == "S" || choice == "s") break;
		if (choice == "P" || choice == 'p') break;
	}
	return choice;
}

-- try to be consistent and remember what quotes around letters mean versus apostrophes.

Intrade 33 Junior Poster

You're trying to compare a string with a char--

//...

char humanChoice(){
//...
}

//...
	// declare variables
	string human;
//...

 human = humanChoice(); // assignment, not construction - http://www.cplusplus.com/reference/string/string/operator=/

if (human == 'Q' || human == 'q') break; // doesnt work - string == char isn't defined

-- The easy solution is to change the types of your declared variables in main--

// declare variables
	char human;
	char computer;

http://www.cplusplus.com/reference/string/string/string/
http://www.cplusplus.com/reference/string/operators/

Intrade 33 Junior Poster

You need to add/initialize sum--

int sum = 0;

-- and then change your code to accommodate one of your requirements --

#include <iostream>
#include <iomanip>

using namespace std;

int main() 
{
    double firstNum, secondNum;   // Operands
    char oper;					  // Operator
    int  result;                  // Resulting value
    int sum = 0;                  // sum
    
    while (cin >> firstNum >> oper >> secondNum) 
	{
        switch (oper) 
		{
            case '+': result = firstNum + secondNum;
                      sum+= result;
					  break; 
            case '-': result = firstNum - secondNum;
                      sum-= result;	  
                      break;
            default : cout << "Bad operator '" << oper << "'" << endl;
                      continue;  // Start next loop iteration.
        }
		
     cout << result << endl << endl;
     cout << "Sum: " << sum << endl << endl;
    }


	system("pause");
    return 0;
}

-- you can easily implement undo by using a Stack of Pairs (or a stack of structs with char variable and int variable) (The left side of the datum contains the operand, the right side contains the value returned by firstNum + or - secondNum. This way you can pop the datum from the stack and do the opposite operation on sum with the value. Obviously disable undo when the stack is empty).

I wont show you how to do this. There are other methods, but this is a fairly decent one you should look up and try out for your calculator.

Intrade 33 Junior Poster

Read "The C++ Programming Language" by Bjarne Stroustrup.

Intrade 33 Junior Poster

My name... I'd rather not say. Intrade is fine. I would prefer to be referred as this name than my others anyways.

I'm a very shy individual.

I have a great need to become not just a good programmer, but a good Computer Scientist.

I apologize for my past deeds here on Daniweb. I gave out code by accident once and was marked down for it for good reason. Not to mention the code quality probably was not very good compared to the professionals whom I want to learn from.

I'm going through a severe depression, yet again. I've made the mistake of wasting away my life from depression and I won't do that again. Instead, I'm going to use the energy accumulated from the focus of depression towards learning Computer Science.

I'm definitely not the best programmer nor Computer Scientist, but there is one thing I've learned well so far... there's a difference between learning something and teaching it. When you learn something, you typically use what you've learned now and then and sometimes quite often... but when you [correctly] teach something you relearn the details and become much more involved with the subject. I found that by explaining specific details to people on Daniweb I relearned the subject at hand myself and also gained more knowledge from professionals. When I see professionals explain something in fine detail, I know that they know what they're talking about and that their knowledge of the subject …

Intrade 33 Junior Poster

Okay, I have a question.

What exactly does the i at the end represent for each of your patterns? Just the literal i, or does it have some other meaning?

I don't see it mentioned on Boost regex, nor have I encountered it in Lua.

I don't expect you to answer anytime soon... you're asleep ;p

Intrade 33 Junior Poster

Hello guys! I'm trying to learn the Boost regex library for a more-convenient means of error-checking and the asio library to allow a fairly portable-means of manipulating data over TCP/IP.

My goal is to retrieve the file information from a website (basically http layer).

My first problem is determining the Regex for an IP. I've tried the following Regex's--

"^w{3}\\.{1}[.]+\\.{1}[.]+"
"^w{3}" // got desperate here, and it didn't work!

-- the first one I tried to match against 3 w's at the start of the line, a period, and then other characters, then another period and finally whatever other characters to follow. I'm aware that some websites don't require the www prefix, I just wanted to do something interesting for checking to experiment around. Apparently, I misunderstood the Regex syntax I've looked up on Wikipedia and Boost/regex. Any help with this would be much appreciated.

My second problem is the understanding of how to make my client-program retrieve a server-file from the internet much like a web-browser does. I can't stress enough that I'm mainly experimenting with this to see if it can be done, so hopefully someone that is network savvy and/or someone with experience with Boost asio can help me with the next part. Here is my code (and please bare with me I know it's ugly right now, but I have a format for debugging each function that is really helpful to me)--

#ifndef INTERNET_DATA_PARSER_H
#define INTERNET_DATA_PARSER_H

#include <string>
#include <map>
#include …
Intrade 33 Junior Poster

This pseudocode is much more intuitive. Please forgive me for the previous mistake(s).

//This vector is a vector where {2, 4} is the largest reoccurring sequence
//{1, 8, 3, 2, 4, 5, 7, 2, 4, 5, 8, 9, 2, 4}

//I'm not that good with Pseudocode, but how about this?

// returns the length of the string
function length(string[0... n-1]);

// Input: a map with string keys and int values
// Output: 2 values - the size of the largest sequence and
// a string with the values of the largest sequence
function FindLargestSequence(map[0... n-1])

	largestValue = 0
	largestSequence = ""

	for each key k value v in map

		if v >= largestValue && length(k) > length(largestSequence)
			
			largestValue = v
			largestSequence = k
		end
	end

	return largestValue, largestSequence
end

// Input: a vector of length n
// Output: 2 values - the size of the largest sequence, and 
// a string with the values of the largest sequence
function VectorSequence(vector[0... n-1])

	s = ""

	for largestSequence = 1, largestSequence <= n, largestSequence = largestSequence + 1

		for i = 0, i < n, i = i + largestSequence

			for j = 0, j < largestSequence, j = j + 1

				s = s + vector[i+j]

				if j != largestSequence - 1
					s = s + ","
			end

			if occurrenceMap[s] == NULL

				occurrenceMap[s] = 0
			else

				occurrenceMap[s] = occurrenceMap[s] + 1
			end

			s = ""
		end

		
	end

	return FindLargestSequence(occurrenceMap)
end
Intrade 33 Junior Poster

Sorry, the line - "v < largestValue" is supposed to be "v > largestValue"

I dun goof'd >_<

Edit: Another problem--

if occurrenceMap[s] != 0

				occurrenceMap[s] = 0
			else

				occurrenceMap[s] = occurrenceMap[s] + 1

if occurrenceMap[s] != 0 is supposed to be if its NULL

Again, I'm sorry. The whole point is that you can use a map to help you with this kind of problem.

Intrade 33 Junior Poster

I am not that great with pseudocode, but this is a possible process. Basically you can use a map with string keys and int values to keep track of each sequence and if the same sequence is run into on the map, increment the value by 1--

// Input: a map with string keys and int values
// Output: 2 values - the size of the largest sequence
function FindLargestSequence(map[0... n-1])

	largestValue = 0
	largestSequence = ""

	for each key k value v in map

		if v < largestValue
			
			largestValue = v
			largestSequence = k
		end
	end

	return largestValue, largestSequence
end

// Input: a vector of length n
// Output: 2 values - the size of the largest sequence, and 
// a string with the values of the largest sequence
function VectorSequence(vector[0... n-1])

	largestSequence = 1
	s = ""

	for h = 0, h < n, h++

		for i = 0, i < n, i = i + largestSequence

			for j = 0, j < largestSequence AND i + largestSequence < n, j++

				s = s + vector[i+j]

				if j != largestSequence - 1
					s = s + ","
			end

			if occurrenceMap[s] != 0

				occurrenceMap[s] = 0
			else

				occurrenceMap[s] = occurrenceMap[s] + 1
			end

			s = ""
		end

		largestSequence = largestSequence + 1
	end

	return FindLargestSequence(occurrenceMap)
end
Intrade 33 Junior Poster

It's called on line 16 of the original code.

I see I am yet again ignored. I'll leave this topic to the pros. Good day.

Intrade 33 Junior Poster

>>where do you initialize the size of m_vParentPop2 (your DNA vector)?
Pre-Determining/Initializing the size of a vector isn't necessary. It gets dynamically set as you push values into the vector.

As in--

http://www.cplusplus.com/reference/stl/vector/vector/

-- nowhere in his code did I see construction of a vector with allocated space to set the size param. Nowhere for that particular vector was a push_back called.

Calling the [] operator without proper initialization can't be good.

Example--

#include <vector>

using namespace std;

int main(){
	
	vector<int> n;
	int x = n[0];
	return 0;
}
Intrade 33 Junior Poster

I'm really curious about this, but where do you initialize the size of m_vParentPop2 (your DNA vector)?

Just glancing at the code, I can only see that as the problem. I don't see anywhere where you've pushed DNA pointers into the vector before accessing its [] operator.

I'm using TextPad Search function and only see two occurrences of the use of m_vParentPop2 and each time it's used it's being accessed via [] operator... no initialization spotted.

Intrade 33 Junior Poster

Intrade, this is why we don't tinker with people's code and post the answer. You just finished the program for him and he passes on your work, not his.

My apologies. I just got done reading Narue's post http://www.daniweb.com/forums/thread78223.html

Next time I'll just point out the problem(s).

Intrade 33 Junior Poster

That's why default-types exist.

Consider the Map interface, it is declared as follows--

template < class Key, class T, class Compare = less<Key>,
           class Allocator = allocator<pair<const Key,T> > > class map;

Notice how class Compare = less<Key> and class Allocator = allocator<pair<const Key, T>>

That means, if someone calls the Map with only 2 template parameters, the other 2 are assigned the default types however the user has a choice of also assigning those types to his/her own specific classes that satisfy the template parameters.

So the user has several options on how to use the Map template.

If you want to allow several options (via template parameters) on how a user constructs your list objects, you would want something like--

template <class LISTDATA, class LISTKEY = int>

-- unfortunately you must define from R-to-L in template parameters and I don't think 'gaps' are allowed. But this way you can explicitly tell your class what type of key you want when you want to use that option. With the above change, this should be allowed--

list <unsigned int> l; // data-type 'unsigned int', key 'int'
list <unsigned int, short> m; // data-type 'unsigned int, key 'short'

-- although this might seem counter-intuitive upon declaration and usage, keep in mind the map template itself does not make a default key either.

Intrade 33 Junior Poster

I said omit all occurrences of spots, not just the one in main.

I was tinkering around with your program some--

#include<iostream>
using namespace std;

const int num_rows = 3;
const int num_colm = 3;
int inputCount = 0;

bool taken[9] = {false, false, false, false, false, false, false, false, false};

void xPlayer(char board[][num_colm], int);

void oPlayer(char board[][num_colm], int);

bool checkBoardX(char board[][num_colm], int);

bool checkBoardO(char board[][num_colm], int);



int main()
{
        int X;
        int O;

        char board[num_rows][num_colm] = {{1,2,3},{4,5,6},{7,8,9}};

        cout << "TIC-TAC-Toe" << endl;
        for(int i=0; i < num_rows; i++)
        {
                for(int j=0; j<num_colm; j++)
                {
                        board[i][j] += 48;
                        cout << board[i][j];
                        cout << "   ";
                }
                cout << endl;

        }
        cout << "^Beginning Board^"<<endl;

		while(true){

			if(!checkBoardO(board, num_rows) && inputCount < num_rows * num_colm)
				xPlayer(board, num_rows);
			else break;
			if(!checkBoardX(board, num_rows) && inputCount < num_rows * num_colm)
				oPlayer(board, num_rows);
			else break;
		}

        if(checkBoardX(board, num_rows))
                cout << "Player X wins" <<endl;
        else if(checkBoardO(board, num_rows))
                cout << "Player O wins" <<endl;
		else cout << "Neither player won!" << endl;

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

void xPlayer(char board[][num_colm], int num_rows)
{
        int move;

        for(int i = 0; i < 3; i++)
        {
                for(int j = 0; j < num_rows; j++)
                {
                cout << board[i][j];
                cout << "   ";
                }
                cout << endl;

        }

		bool validMove;

		do{
			validMove = true;
			cout << "Player X, please make your move (1-9): ";
			cin >> move;

			validMove = (move > 0 && move < 10);
			
			if(!validMove){
				cout << "Your pick was not in the range 1 - …
WaltP commented: Good job! Now he can cheat his way to an A -3
Intrade 33 Junior Poster

You can completely omit the need to place your chars into ints for display by simply adding 48 to all of your chars in your 2D char array--

int X;
        int O;

        char board[num_rows][num_colm] = {{1,2,3},{4,5,6},{7,8,9}};

        cout << "TIC-TAC-Toe" << endl;
        for(int i=0; i < num_rows; i++)
        {
                for(int j=0; j<num_colm; j++)
                {
                        board[i][j] += 48;
                        cout << board[i][j];
                        cout << "   ";
                }
                cout << endl;

        }

-- now you have no need for any occurrence of "spots" and can simply output your [j] character(s).

Intrade 33 Junior Poster

hello..

What do we mean by binary search and how we can do it using C++

thanks..

1) http://en.wikipedia.org/wiki/Binary_search_algorithm

2) http://www.fredosaurus.com/notes-cpp/algorithms/searching/binarysearch.html

I found these sources off of google. I really don't mean to sound mean, but before asking a question on a forum try exhausting other easy means of answering your question to save you the wait time ;p

Intrade 33 Junior Poster

How do you want people to access your 4D vector points? At first glance I'd think something like this would work for you--

float operator [] (int index)
{
	index = (index >= 0) ? ( (index <= 3) ? index : 3 ) : 0;
	switch(index){
		case 0:
			return f1;
		case 1:
			return f2;
		case 2:
			return f3;
		case 3:
			return f4;
	}
}

-- but do you want to be able to modify your 4D vector's internal values when calling the operator or not? Or, where do you want people to start in your operator for finding the points?

Intrade 33 Junior Poster

Is there a specific reason you're using iostream.h in the brackets? You typically omit the .h but you also forgot to declare the namespace you're working in. Lastly, the function that takes "Test" I believe takes a slightly bigger datatype than const char* try prefixing it with L--

//...
#include <iostream>

using namespace std;

//...

hEvent = CreateEvent(NULL,FALSE,FALSE,L"Test");

//...
Intrade 33 Junior Poster

I'm fairly new to Boost. I would like to use the Regex library.

I wanted to follow this guide but it seems that it supports other versions of VC++.

http://www.boost.org/doc/libs/1_44_0/libs/regex/doc/html/boost_regex/install.html

EDIT: I tried finding a link to VC++ 6.0 and I can't find it >_<, apparently Microsoft is no longer allowing it to be downloaded?

http://social.msdn.microsoft.com/Forums/en-US/vcgeneral/thread/263cf0ae-9e96-4004-9052-7260816865b8/

EDIT2: Do I absolutely have to "install" Regex? I know this might be a stupid question but I'd like to find workarounds.

Thank you.

Intrade 33 Junior Poster

If | Original Servings / Desired Servings | = rate then
rate = 1 / | Desired Servings / Original Servings |, but you don't account for this in your code.

//modify -1 below to be your new calculated value.
return (rate - 0.1 * (1 - (1/rate)));
Intrade 33 Junior Poster

Maybe something like this will work?

class a;
class b;

class a
{
b* bpointer;
};

class b
{
a* apointer
};
miturian commented: friendly and helpful +1
Intrade 33 Junior Poster

How about writing some ideas on paper that you would like to personally code and then learn what you need to get the job done?

Although this might seem daunting, it really pays off when you finish the project and you'll learn how to arrange your thoughts into Java code and be capable of writing in it more efficiently. You'll also gains some tools to write different code using similar ideas/solutions you've come up with.

Intrade 33 Junior Poster

Whoops! Lag caused a double post, my apologies.

Intrade 33 Junior Poster

Should I worry about namespacing when porting the code, or should I omit that as well? For example--

namespace EquationSolver{

	static int mode = 0;
	static bool isProperEquation(string);
	static string es_solve(string);
	static enum {MODES_SUPPORTED = 1};
	static string solved = "";

	__declspec(dllexport) const char* solve(const char*);
	__declspec(dllexport) void setMode(const char*);
	__declspec(dllexport) void setMode(int);


	bool isProperEquation(string equation){

		return false; // TODO determine invalid input
	}

	string es_solve(string equation){

		return ""; // TODO solve the problem
	}

	const char* solve(const char* s){

		solved = "";

		if(!EquationSolver::isProperEquation(s))
			return s;
		else{
			solved = es_solve(s);
			return solved.c_str();
		}
	}

	void setMode(const char* s){

		if(string(s).compare("N"))
			mode = 0;
		else mode = 0; // Only 1 mode is supported for now
	}

	void setMode(int m){

		mode = m < MODES_SUPPORTED ? ((m >= 0) ? m : 0) : MODES_SUPPORTED - 1;
	}
};
Intrade 33 Junior Poster

You forgot to add return average to your function--

int calcAverage()
{
int sum=0;
int average;
int TESTVALS[5] = {2, 18, 1, 27, 16};
for(int i = 1; i < 5; i++)
sum+= TESTVALS[i];
average= sum/5;
return average;
}

-- so its possible that due to the lack of the return statement the function was assigned some space of an int that wasn't initialized.

Intrade 33 Junior Poster

In what way do you want it to bounce? Up-and-down or around the screen, or some other implementation?

If it's just around the screen, you can give the object velocity (some dx and some dy) where dx is the rate at which it travels along the horizontal (and its horizontal direction), and dy is the rate at which it travels along the vertical (and its vertical direction).

If you're just outputting this to the console screen, you're going to probably need to call some windows functions or lots (and I mean lots) of formatting functions if you plan to do this without windows.h and no GUI library. You need to find a way to determine a position on the console window and then calculate its new position per increment of the text moving.

If you're using a GUI library, this will be a lot easier.

In either case, you're going to have to have some bounds. You want the text to bounce as it hits the edges of the screen. Basically when the text "hits" the left side of the screen or right side be sure to reverse the direction of dx, and likewise if the text "hits" the top or bottom reserve the direction of dy.

If its up and down you'll have to determine its initial height, gravity (downward acceleration), mass (can be dummy mass like 1), its upward acceleration from bouncing off the ground, and its desired final return height on its …

Intrade 33 Junior Poster

What I want to know is if I can call a function defined in a C++ class in Visual Basic through a .dll generated from VC++2010?

Is this possible, or do I need to define the .dll with C++ raw functions outside of a class?

For example, my class looks like this--

//...

typedef class EquationSolver{

	private:

		static int mode;
		static bool isProperEquation(string);
		static string _solve(string);
		static enum {MODES_SUPPORTED = 1};

	public:

		static __declspec(dllexport) string solve(string);
		static __declspec(dllexport) void setMode(string);
		static __declspec(dllexport) void setMode(size_t);
} ES;

int ES::mode = 0;

//...

Will I be able to call any of the public functions in VB, or do I have to write it using C-like function definitions (basically outside of a class and global variables)?

Intrade 33 Junior Poster

Okay, how about this.

Make a function that accepts an IP Address, and the Subnet (Subnet Address and Mask) and have it return a bool. It returns true if the IP Address exists in the subnet, or false if it doesn't.

bool ValidIP(const string& ipAddress, const string& subnetAddress, const string& mask){

// ...
   bool validIPAddress = false;
// ...

   return validIPAddress;

}

... Or are you asking about the algorithm to determine whether an IP Adress exists in the subnet or not?

Also, the following source(s) may help:

http://techpulp.com/2008/10/how-to-validate-ip-address-in-c/

http://beej.us/guide/bgnet/output/html/multipage/inet_ntopman.html

http://en.wikipedia.org/wiki/Subnetwork

http://www.subnet-calculator.com/

Intrade 33 Junior Poster

That's because your function returns 0 and when you say cout << sum << endl, sum was passed 0 from the function and then it was pushed to the output stream.

Your function doesn't really need to return anything. You can make it void and simply call the function. There is no need to cout << sum << endl;

Intrade 33 Junior Poster

You were almost there. Try this code--

#include<iostream>
#include<conio.h>
using namespace std;


void addingarray (int *a, int *b, int *c, int size) // this is my function
{
	for(int i=0;i<size;i++)
		 c[i]=a[i] + b[i];

	for(int j=0; j<5; j++)
		 cout<<*(c+j)<<endl;
	
	
}
 int main ()
 {
	 
	 int num1 [5] ={1,2,3,4,5}; // i initialized my array
	 int num2 [5] ={2,5,4,6,4};
	 int num3 [5];
	 int *ptr1=num1; // i equated the content of the array to the pointer
	 int *ptr2=num2;
	 int *ptr3=num3;	
	 
	 addingarray(ptr1, ptr2, ptr3, 5); 
    
   getch();
	 }

Remember when you are calling a function you have to supply the function with the parameter requirements. In this case ptr1, ptr2, ptr3 and 5 were passed into the function addingarray (because they fulfilled the function parameter requirements) to be used for the calculation.

Intrade 33 Junior Poster

Please post your newest code

Intrade 33 Junior Poster

I'm assuming you're outputting the address of the array (maybe) and not the value of the array.

In this case print the contents of the array.

for(int i = 0; i < 5; i++)
   cout << ptr3[i] << flush;
Intrade 33 Junior Poster

leave the code --

// here i tried to sum the arrays
	for(int i=0;j<size;i++)
		 c[i]=a[i] + b[i]; // and assign the sum to third empty array

in the addingarray function because that's where the parameters size, c, a and b exist.

Omit the sizeof(*a), you don't need this because you're pasing the size to the function with the parameter 'size'--

// This is OKAY
int addingarray (int *a, int *b, int *c, int size) // this is my function
{
	 for(int i=0;i<size;i++)
		 c[i]=a[i] + b[i]; // and assign the sum to third empty array

         return 0;// not sure why you changed it to return int but make up for it here
}
Intrade 33 Junior Poster

For your function addingarray, try using actual pointers for parameters...

void addingarray( int* a, int* b, int* c, int size){ 

//...

}

Also you are trying to push a void function into the outputstream which I don't think the compiler will like. Omit that.

In the function addingarray, assuming you've made the above fixes, the line(s)--

*ptr1=a; // i tried to assign the contents of the arrays to the variables
	*ptr2=b;
	*ptr3=c;

--do not make sense. Omit that--

// here i tried to sum the arrays
	for(int j=0;j<size;j++)
		for(int i=0;i<size;i++)
		 c[i][j]=a[i][j] + b[i][j]; // and assign the sum to third empty array

For the sake of simplicity leave your declarations/definitions in main. Omit--

int num1, num2, num3; // i declares by array name and type
int*ptr1,*ptr2,*ptr3; // i delacred the type of the pointers

--and instead declare the types in main then assign them--

int main ()
 {
	 
	 int num1 [5] ={1,2,3,4,5}; // i initialized my array
	 int num2 [5] ={2,5,4,6,4};
	 int num3 [5];
	 int* ptr1=num1; // i equated the content of the array to the pointer
	 int* ptr2=num2;
	 int* ptr3=num3;
        
//...
}

EDIT: I just noticed you're iterating through your arrays as if they are 2Dimensional. You're only dealing with 1 row of ints so you need not iterate through array[j] but jut array--


// here i tried to sum the arrays
	for(int i=0;j<size;i++)
		 c[i]=a[i] + b[i]; // and assign the sum to third empty array

There are many …

Intrade 33 Junior Poster

It looks good.

Nobody else responded. I didn't want you to feel ignored ;p

Intrade 33 Junior Poster

The following code is an example of how you could use a map to solve your problem.

#include <iostream>
#include <map>
#include <string>
#include <Windows.h>

using namespace std;


int main(){

	map<string, WORD> myMap; // map where "strings" are used as keys and 16-bit ints are returned
	string arr[] = {"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"};
	map<WORD, string> reverseMap; // just for convenience
	enum {DOW = 7};

	for(int i = 0; i < DOW; i++){
		myMap.insert(pair<string, WORD>(arr[i] , static_cast<WORD>(i) ));
		reverseMap.insert(pair<WORD, string>(static_cast<WORD>(i), arr[i]));
	}

	for( map<string, WORD>::iterator it = myMap.begin(); it != myMap.end(); it++)
		cout << (*it).first << " => " << (*it).second << endl;

	WORD dayOfWeek = static_cast<WORD>(5);

	if( myMap["Saturday"] == dayOfWeek)
		cout << "Today is Saturday!" << endl;
	else{

		cout << "Today is not Saturday, but it is " << reverseMap[dayOfWeek] << "!"<< endl;
	}



	cin.get();
	return 0;
}
Intrade 33 Junior Poster

Sweet deal. At least you managed to figure it out!

Oh and no I have nothing to do with that website ;p

Jsplinter commented: thanks +1
Intrade 33 Junior Poster

You could try having a mapping of strings to numbers and upon entering a string as the key the map returns the value as an integer that the day represents.

Intrade 33 Junior Poster

I've never seen this issue before, but I did google something interesting about __w64

Source: http://msdn.microsoft.com/en-us/library/s04b5w00%28VS.80%29.aspx


Some more information on your Data type (and maybe compiler settings) might shed some light on this issue...

Intrade 33 Junior Poster

Okay, in the real world what happens when a vending machine makes a sale (under ideal conditions)?

-The amount of money the machine has stored goes up (but I do not think your implementation has this feature so it can be ignored?)
-The amount of the product in the machine goes down
-(and if someone steals from the machine, it grows arms and legs and whirls around screaming "DANGER! DANGER Will Robinson!"... okay forget this part)

All you have to do every time you make a sale is check to see if there is at least 1 product left in the machine per transaction and if there is, deduct the amount of that machine by 1.

You should write a function for your class (if you're allowed) that shows the remaining amount of the product in the machine each time you sell a product.

Intrade 33 Junior Poster

I think the problem may be the way you're abstracting the code.

Why are vending machines named after specific products? Why not have a Vending machine that CONTAINS products (and a certain amount of them), and when a sale is made the product amount for that particular product is deducted and the ProfitChange amount increases by the amount the product is sold for.