jesseb07 64 Junior Poster

You have two same functions in class

class Object
{
protected:
enum ID {OBJECT, CAVE, MONSTER, WUMPUS, HERO, GUN, BAT}; //maybe it better place outside the class?
Coordinates* _my_coordinates;
void id(ID id) //first declaration
{
this->_my_id = id;
}
public:
explicit Object(s_int coordinate_x = 0, s_int coordinate_y = 0);
virtual void move(Direction, u_int distance = 1) = 0;
ID getId() const //redeclaration(renamed)
{
   return _my_id;
}
const Coordinates* location() const 
{
   return _my_coordinates;
}
virtual ~Object(void);

private:
    ID _my_id;
};

this is a reformed code

Use get- and set- methods, like setId(), and getId()

unfortunately, that is completely preference, many people use function overloading for their respective getters and setters

void RandomObject::Value(int newValue) { _value = newValue; } //setter
int RandomObject::Value() { return _value; } //getter

this is entirely correct. Note the different function signatures? There's no problem with how that is set up. BUT, if you did feel like making the switch to the explicit get-set functions, don't forget to change the setter too ;)

~J

jesseb07 64 Junior Poster

you will also need to define x, y, a, and first before you can use them in main()

jesseb07 64 Junior Poster

if I understand correctly, try adding this just before your return statement in "int main()"

cin.get();

that will wait for you to review the data and press enter before exiting the program. As it is now as soon as it's done with all of it's tasks, it closes instantly.

~J

jesseb07 64 Junior Poster

a couple things I see, first of all, please see the link in my signature for the rules regarding code tags etc, it makes it MUCH easier for us to help you if we can see your code in a comprehensible manner. Second, I don't think this would compile, so if you get any compiler errors, please post those as that is going to point where 90% of the problem is coming from. Ok, here's your code with code tags:

#include <iostream>
using namespace std;

calculate(int x[][],int y[][]);

enterData()
{
    int x[2][2];
    int y[2][2];
    int t[2][2];

    for(int i=0;i<2;i++)
    {
        for(int j=0;j<2;j++)
        {
            cout<<"enter array num1"<<endl;
            cin>>x[i][j];
            cout<<endl;
        }
    }

    for(i=0;i<2;i++)
    {
        for(int j=0;j<2;j++)
        {
            cout<<"enter array num2"<<endl;
            cin>>y[i][j];
            cout<<endl;
        }
    }

    calculate(x,y);
    return 0;
}

int calculate(x[][],y[][])
{
    for(int i=0;i<2;i++)
    {
        for(int j=0;j<2;j++)
        {
            t[i][j]=x[i][j]-y[i][j];
        }
        displayResult(t)
        cout<<endl;
    }
}

displayResult(int t)
{
    cout<<t<<endl;
}

problems I see: you have no main() function. I am assuming you were going for enterData() to act as that.

Second, you have to return type for your calculate function template or for your displayResult and enterData implementations.

what I mean by that is:

calculate(int x[][],int y[][]); //this
int calculate(int x[][],int y[][]); //should be this

displayResult(int t) //and this
{..}

void displayResult(int t) //should be this
{..}

enterData() //and this
{..}

int enterData() //should be this
{..}

and the last thing that I saw is that when you are passing a multidimensional array, you have to declare all the sizes of …

jesseb07 64 Junior Poster

your boolean logic is ill-formed inside of your if statements, instead of

if(a==R||r)
//etc.

it should be

if((a == R) || (a == r))
//etc.

how your first logic reads is "if a equals R or if r".
how I think you wanted your logic to read is "if a equals R or if a equals r"

but yes, as wildgoose has mentioned also: r, R, g, G, y, Y will all be the compiler default value of int, they are uninitialized thus making them unsafe for comparisons.

hope that's helpful

~J

jesseb07 64 Junior Poster

When my try to rebuild my program i m getting this errors

1>Linking...
1>MSVCRTD.lib(crtexe.obj) : error LNK2019: unresolved external symbol _main referenced in function ___tmainCRTStartup
1>C:\Users\agaba\Documents\Visual Studio 2005\Projects\car\Debug\car.exe : fatal error LNK1120: 1 unresolved externals
1>Build log was saved at "file://c:\Users\agaba\Documents\Visual Studio 2005\Projects\car\car\Debug\BuildLog.htm"
1>car - 2 error(s), 0 warning(s)

my code

// Short-term parking at the airport, from 4am to midnight.

#include <iostream>
 using namespace std;
 // function

 void AskTimeIn(int *pHourIn,int *pMinIn);
 void AskTimeOut(int *pHourOut,int *pMinOut);
 void write(int hoursIn,int minsIn,int hoursOut,int minsOut);

int maint()
 {
  int hoursIn, minsIn,hoursOut, minsOut;

  // difine  fuction


  AskTimeIn(&hoursIn,&minsIn); //time in function.

  AskTimeOut(&hoursOut,&minsOut);//time out function.

  write(hoursIn,minsIn,hoursOut,minsOut);// write result function.

return 0;
 }

void AskTimeIn(int *pHourIn,int *pMinIn)
{
 char colon;
    cout <<"\n Enter Time  in ,H:M format: ";
    cin >>*pHourIn>>colon>>*pMinIn;
    cin.ignore();

}
void AskTimeOut(int *pHourOut,int *pMinOut)
{
 char colon;
 cout <<"\n Enter Time out ,H:M format: ";
 cin>>*pHourOut>>colon>>*pMinOut;
 cin.ignore();

}

 void write(int hoursIn,int minsIn,int hoursOut,int minsOut)
 {

  cout<<"\n Time in :"<<hoursIn<<":"<<minsIn;
  cout<<"\n Time out :"<<hoursOut<<":"<<minsOut;
 } 

end quote.

you misspelled main()....

jesseb07 64 Junior Poster

looks like there's a couple things, I don't think that would even compile: comparing a map<int, vector<int> >::iterator to an int inside your loop doesn't seem safe to me. As well as not declaring the map type for your iterator.

anyway, see if this is a good starting point:

map<int, vector<int> > my_map; //I assume these are global or in a class, as you had it
map<int, vector<int> >::iterator it;

void erase(int num)
{
    for(it = my_map.begin(); it != my_map.end(); it++)
    {
        if((*it).first == num)
        {
            my_map.erase(it);
            break;
        }
    }
}

I think that's what you were going for, hope that's helpful

~J

jesseb07 64 Junior Poster

So I changed my code and tried your way to no avail... :/

#include <stdio.h>
#include <cstdlib>
using namespace std;

int main(void)
{
   // with addition of buffers for 3x3 square mask
   // 8x8 original image is now 10x10
   int [][10] imageSquare =                            
   { 
   	{4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
   	{4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
   	{4, 4, 4, 4,48, 4, 4, 4, 4, 4},
   	{4, 4, 4,64,64,64,64, 4, 4, 4},
	{4, 4,17,64,64,96,64, 4, 4, 4},
	{4, 4, 4,64,85,64,64, 8, 4, 4},
	{4, 4, 4,64,64,64,64, 4, 4, 4},
	{4, 4,56, 4, 4,23, 4, 4, 4, 4},
	{4, 4, 4, 4, 4, 4, 4, 4, 4, 4},
	{4, 4, 4, 4, 4, 4, 4, 4, 4, 4}
   };
}

This still gives the same error of comp.cpp:12: error: expected unqualified-id before '[' token.

I mean, it says it's expecting some kind of id before [ which I obviously don't have. But again, I have absolutely no idea what I am missing.

ironically enough, you missed the entire point of my post, change "int[][10] imageSquare" to "int imageSquare[][10]" and your compiler error will go away

jesseb07 64 Junior Poster

do you mean if you don't explicitly create a constructor in your class, or are you referring to constructor overloading?

if it's that you don't explicitly create your own, here's what happens

#include <iostream> //feel free to give this a test to see for yourself, it should compile ok
class Test
{
    public:
        int x;
};

int main()
{
    Test testObject;
    std::cout << testObject.x << std::endl; //this will print the compiler default for an int
    return 0;
}

the object will be created with the default values for all fields.

If you are asking about constructor overloading, it's just like function overloading: the compiler looks at the function signature to choose it for you.

for more info, maybe check out: http://www.cplusplus.com/doc/tutorial/classes/

Hope that's helpful

~J

jesseb07 64 Junior Poster

2 things:
first, arrays are declared like this:

int array[5];
int array2[] = {1, 2, 3, 4, 5};

not like this:

int[5] array;
int[] array2 = {1, 2, 3, 4, 5};

secondly, when dealing with multidimensional arrays, unfortunately you can't do

int array[][] = {{1, 2}, {3, 4}, {5, 6}};

you have to do

int array[][2] = {{1, 2}, {3, 4}, {5, 6}};

you can only leave the first dimension of an array up to the compiler (I'm going off of g++, it COULD be different for other compilers).

since you were googling for an answer, maybe check this out as well:
http://www.cplusplus.com/doc/tutorial/arrays/

Hope that's helpful

~J

jesseb07 64 Junior Poster

I think I know what you're after, try having a variable to hold the totals for each value, something like this maybe:

#include<iostream>
using namespace std;

int main()
{    
    double b = 2.88; 
    double h = 2.4;
    double totalBoards = 0;
    double totalBags = 0;
    double w;
    int p = 25;
    int numOfWalls;

    cout << "How many walls would you like to include? ";
    cin >> numOfWalls;

    for(int x = 0; x < numOfWalls; x++)
    {
        cout << "Enter the width of wall " << x+1 << ": ";
        cin >> w;

        totalBoards += h*w/b;
        totalBags +=  h*w/p;
    }

    cout << "Total number of boards is: " << totalBoards << endl;
    cout << "Total number of bags is: " << totalBags << endl;
     
    cin.get();
    return 0;
}

that should work if I understood you correctly, hope that's helpful

~J

jesseb07 64 Junior Poster

WHAT 12 ?
well 12 is suppose to be of the array for DOB[12].

What n? and the n is to save the crn [n] so that it can matched the DOB [12].

well, that should give you several problems considering you declared DOB to be an array of size 10

int DOB [10]= {1980,1981,1982,1983,1984,1985,1986,1987,1988,1989};

DOB[12] would put you past the end of the array, returning who-knows-what when you try to reference it.

jesseb07 64 Junior Poster

sorry, this is a c++ forum, there is a C# forum located elsewhere on this site

jesseb07 64 Junior Poster

the syntax for a do-while loop is this:

do
{
     //stuff to loop through
}
while(conditions); //note the colon

and maybe consider changing your 'switch' statement to a series of if-else since there's more than 1 or 2 lines of code for each option. I think that's more of a style issue.

Edit: one more thing I noticed

you have your 'for(;;)' but once you run through your do-while loop, you have a break, exiting the for loop. So you only run through the for loop once, maybe look at why you have a break there

Hope that's helpful

jesseb07 64 Junior Poster

Well, I'll try my best. I'm not that keen on compiler workings, but I would be happy to share how I view the process.

in your time.cpp file, you include time1.h. Ignore that you ever wrote time1.cpp for now. if you were to compile it as
g++ time.cpp -o time
naturally the compiler sees the header (time1.h) and looks in time.cpp to give the implementations of those functions. When it doesn't see it, it gives you the error you saw, essentially saying "you said those would be here, but they're not". It gave you that because you only included the "declaration" of the functions.

when you compile the separate .cpp's into objects, for instance:
g++ -c time1.cpp -o time1.o
this makes an object which has BOTH the declaration and implementation of the functions. So when you include "time1.h" in "time.cpp" and compile them as objects, you are essentially telling the compiler how that code relates the the program as a whole. (a puzzle piece and how it fits in the puzzle) When you link the objects together
g++ time1.o time.o -o time
that's when the compiler takes all the individual puzzle pieces together and makes a pretty picture ;)

Hopefully that made sense, I'm sure I made some technical or notation error in there somewhere, but that's how I view it. If you are REALLY curious, I'm sure google can yield some pretty good explanations.

jesseb07 64 Junior Poster

your problem is in how you are compiling it. You need to compile each .cpp file separately into objects and then link them all together at the end. Give this a try (my g++ flags are a bit rusty, but I think they're right)

g++ -c time1.cpp -o time1.o //compile into an object
g++ -c time.cpp -o time.o //compile into an object
g++ time1.o time.o -o time //link objects together

Hope that helps

~J

jesseb07 64 Junior Poster

For some reason, my numbers aren't adding in correctly and it's taking the -1 sentinel value and adding it into the total.

// worthless testing.cpp : Defines the entry point for the console application.
//

#include "stdafx.h"
#include <iostream>

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


int main()
{
int number = 0;
int total = 0;
do
{
	cout<<"Enter a number: ";
	cin>>number;
	total = total + number;
} while (number != -1);

cout<<"Total is:"<<total<<endl;
	return 0;
}

to answer the OP's question, here's why the total is being affected in a way that you don't think it should. Go through your loop and see what's happening sequentially:
1. tell the user to enter a number
2. get the number
3. add the number to the total (regardless of what it is)
4. exit if the number is -1

simple fix (that utilizes 99% of your original code ;) ) :

total = total + number; //change this to:

if(number != -1) //this
     total += number //with this

now here's what's happening:
1. tell the user to enter a number
2. get the number
3. add the number to the total if it's not -1
4. exit if the number is -1

hopefully that's helpful as well, while it pales to tux's thesis :P

there is another way of doing it (for completeness sake) with a conditional break inside of the loop, but can't say it's the preferred …

tux4life commented: Yes, this post is also valuable in this thread :) +13
jesseb07 64 Junior Poster

Well I don't need to return any values other than the bonus amount. So would I make my displayBonus function like

void displayBonus(double &bonus)

?

no, since you are not altering 'bonus' in displayBonus, you don't need to pass it by reference, you also don't need to return it, you're only displaying what it is.

This looked like a good explanation of what passing by reference means if you are a bit confused as to what is actually going on:
http://www.tech-recipes.com/rx/1232/c-pointers-pass-by-value-pass-by-reference/

give that a look over and then you can see when it's needed and when it's not.

~J

jesseb07 64 Junior Poster

global variables ARE a bad idea, which is why it's not the only way to accomplish this with a void function. Try passing things by reference:

void getSales(double &sales); //try this instead
//other functions
 
int main()
{
       //declare constant and variables
       const double RATE = .1;
       double sales = 0.0;
       double bonus = 0.0;
 
       getSales(sales);

       //sales is now whatever you calculated it to be from inside getSales

       //blah blah blah
}

make sure you change your function appropriately (should be simple) and also implement wildgoose's suggestion of a do-while loop. Hope that's helpful

~J

jesseb07 64 Junior Poster
jesseb07 64 Junior Poster

I feel pretty stupid, I found the problem and I know why it's not working in this case and why it does work for my other case (I also know a better alternative, so I guess it's ok). Here was the problem (in case anyone was wondering) and I'll try to explain it without having to show my rather extensive class structure. I have a class Node, one of it's members is 'Row<Node> children' (btw MyFrame also has a member of Row<Node> so this is why it gets called in the first place). So in the constructor of Row where it makes the npos and makes a new Cell<Node>, the Node constructor gets called, and makes a new Row<Node> which, in it's constructor makes a new npos, thus making a new Node, calling it's constructor, and down the infinitely recursive line we go.

I hate when my posts turn out like this, maybe I should extend my 3 hour rule before posting to 2 days ;)

Thanks to those who tried to help me, unfortunately it was unsolvable with the information I provided (incomplete), I tried to not make it so.

~J

jesseb07 64 Junior Poster

thanks for the replies, but it fails before the Show() method, it's in the constructor. And I did isolate the problem further so now the issue has changed scope a little bit. I had forgotten I had done this and it's causing the problem but I don't know why. Here's the issue:

MyFrame has a member of type Row<NodeValue> (Row<T> is my linked list class which has individual cells of type Cell<T>) so in the constructor, it's making that Row and there's where the problem starts.

class MyFrame : public wxFrame
{
	public:
		MyFrame(const wxString& title, const wxSize &size);
		~MyFrame();
		
		Row<NodeDisplay> nodeMap; //it makes this
		//other members
		
	private:
		DECLARE_EVENT_TABLE();
               //other private members
};

//so it goes here: row.h

template <class T> class Row
{
	private:
		unsigned int size;
		Cell<T> *firstCell, *lastCell, *npos; //npos is giving the issue, see constructor
		Row<T> *nextRow, *currentRow, *prevRow;

	public:
		Row();
		~Row();

              //other members
};

template <class T> Row<T>::Row()
{
	firstCell = NULL;
	lastCell = NULL;
	nextRow = NULL;
	prevRow = NULL;
	npos = new Cell<T>();  //this should work but throws the error
	currentRow = this;
	size = 0;
}

I know this method works because I've implemented it on a Map<T> class, so I'm curious why this is causing a problem, suggestions? oh, here's the Cell<T> stuff:

template <class T> class Cell
{
	private:
		Cell<T> *nextCell, *prevCell;

	public:
		T cellValue;

		Cell()	{ nextCell = NULL; prevCell = NULL; }
               //other members
};

Thanks!

~J

jesseb07 64 Junior Poster

hello, got a quick question regarding stack overflow (I honestly don't know if this is more suited for a wxWidgets forum, once you see what I mean, but I figured I'd try here first). I was tweaking my linked list class and testing it in a testing harness program I wrote for it (performance, making sure functions work, etc) when I now get stack overflow errors when I start the debugger (VS2008 PRO). Here's the message:

Unhandled exception at 0x772e0e5a in Tester.exe: 0xC00000FD: Stack overflow.

I traced it back to the constructor of the window frame:

bool MyApp::OnInit() //initializer
{
	MyFrame *mainFrame = new MyFrame(wxT("Test Harness"), wxSize(700, 600) ); //breakpoint 1
	mainFrame->Show(true);
	
	return true;
}

//...
MyFrame::MyFrame(const wxString& title, const wxSize& size) : wxFrame(NULL, wxID_ANY, title, wxDefaultPosition, size)
{ 
	CreateStatusBar(); //breakpoint 2
	SetStatusText(wxT("Performance Data"));
	
	//panels and controls
}
//...

//malloc.c

//...
#ifdef _WIN64
    return HeapAlloc(_crtheap, 0, size ? size : 1);
#else  /* _WIN64 */
    if (__active_heap == __SYSTEM_HEAP) {
        return HeapAlloc(_crtheap, 0, size ? size : 1); //VS said this line was the problem
    } else
    if ( __active_heap == __V6_HEAP ) {
        if (pvReturn = V6_HeapAlloc(size)) {
            return pvReturn;
        }
    }
//...

I would start at breakpoint 1 but never hit breakpoint 2, which means it must be failing in the constructor (memory allocation from the inherited constructor).

It started failing after I added another operator function of my linked list (++ so I wouldn't have to keep saying 'iterator = iterator->NextCell()' ), even though …

jesseb07 64 Junior Poster

2 options for this problem:

1. Add

cin.get();

just before your return. This waits for user input before exiting the program.

2. Run the program manually from a terminal. Then you can see the output even if the program exits

~J

jesseb07 64 Junior Poster

an alternative to the explicit initiation, is you could change your while loop to a do-while:

#include <iostream>
#include <ctime>
using namespace std;
       
 int main()
{
      int random;
      int guess;
       
      srand(static_cast<unsigned int>(time(0)));
      random = rand()%7+1;
       
      std::cout << "Guess my number! (1-7)\n";
       
      do
      {
            std::cin >> guess;
            std::cin.ignore();
            if (guess < random)
            {
                  std::cout << "Too Low!!!\n";
            }
            if (guess > random)
            {
                  std::cout << "Too High!!!\n";
            }
            if (guess == random)
            {
                  std::cout << "You Won!!! My number was: "<< random << "\n";
                  std::cin.get();
            }
      }
      while (guess != random);
}

just an alternative if you were curious

~J

jesseb07 64 Junior Poster

I personally generally use an EVENT_TABLE if I have a large number of events for a class ( > 5 or so), but if I only have 1 or 2 I generally use Connect (or I have a complicated gui, lots of enabling/disabling etc). I've just found it to look cleaner: prevents a ridiculous amount of event tables but if there's a ton of events it's easier to keep them straight in an event table. That's my preference, there are some different things that can be done with connect so it's not a straight substitute either way, but if you want something more than that, here's explaining the subtle differences:

http://wxwidgets.blogspot.com/2007/01/in-praise-of-connect.html

Also, another interesting bit of info is that in my wxwidgets book, written by the creators, all of their examples (that I've seen) use event tables. It's possible that there's performance differences (significant I mean) since event tables are static routing and connect is dynamic but I have yet to see anything definitive so I'm going by what I like :)

hope that's helpful

~J

Nick Evan commented: Good post +18
jesseb07 64 Junior Poster

instead of using the ascii codes which would get a bit more complicated when you add numbers because of the disconnect between the codes (since numbers are 48-57 and letters 97-122), why don't you try something like the following as a starting point:

string random_letter(int length) 
{
     const string values = "abcdefghijklmnopqrstuvwxyz";
     const int valuesSize = 26;
     string s;

     for (int i = 0; i < length; i++) 
     {
          s += values[rand() % valuesSize];
     }

     return s;
}

then you can add whatever characters you want (numbers), just a suggestion.

~J

jesseb07 64 Junior Poster

you just declare password as a char ( char password ) .
Now compile it it is erorr free.
I hope you enjoy it.

that is assuming their password is something like 'b' or '7' (I hope it's not) and just because something compiles doesn't mean it works ;)

this compiles:

#include <iostream>
#include <vector>
using namespace std;

int main()
{
     vector<int> values;
     values.push_back(1);

     for(int x = 0; x < 10000; x++)
          cout << values[x] << endl; //segfault anybody?

     return 0;
}

OP: I'm with Darth, change a to a string

jesseb07 64 Junior Poster
for(int i=1;i>=10;i++)
	
for(int i=1;i>=10;i--)

}

besides arrays you should also brush up on for loops...

neither of those will even be entered into (seeing as 1 is NOT greater than or equal to 10). For the first loop you'd need to switch it to this for your code to at least make sense:

for(int i = 0; i < 10; i++)

and your second loop

for(int i = 9; i >= 0; i--);

notice I switched it from going from 1-10 and 10-1 to 0-9 and 9-0 because arrays use a 0 index for the first element. Look over this loop and see if you can get the idea of how it's getting filled

int values[10];

for(int x = 0; x < 10; x++)
{
     values[x] = x+1; //values[0] = 1, ... values[9] = 10

     std::cout << "values[" << x << "] = " << values[x] << std::endl;
}

hope that's helpful

~J

jesseb07 64 Junior Poster
void checkWords(char*);
void printWords(char*);

void checkWords(char *argv[] )
{
}

void printWords(char *argv[] )
{
}

you forgot to change both declarations of the functions, so the compiler is looking for checkWords(char*) but you only had checkWords(char**).

try:

void checkWords(char*);
void printWords(char*);

void checkWords(char *argv )
{
    //etc
}

void printWords(char *argv )
{
    //etc
}
jesseb07 64 Junior Poster

looks like you're passing the wrong types to the function (in your implementation). Here's your declaration:

void checkWords(char**); //or void checkWords(char *blah[])

however in your implementation you are only passing it a single char* (not char* array or char**)

checkWords(argv[1]);

Solutions:
A) change your declarations to 'void checkWords(char*);' so that the types will match, or
B) pass your entire argv into the function 'checkWords(argv)'

hope that's the issue, if it's not could you post the compiler output?

jesseb07 64 Junior Poster
void checkWords()
{
    int totalWords = 0, uniqueWords = 0;
    char *argv[1];
    bintree<word> tree;

    ifstream file( argv[1] );

you are trying to use the argument passed to main, but all you are doing is creating a new variable with the same name (but with a different scope and completely different value). Try passing your 'argv' variable from main into your checkWords function.

void checkWord(char *argv[]);

Also, are you able to pinpoint where it locks up?

jesseb07 64 Junior Poster

in your revised set of code, try removing the following line:

int main(int, char**);

and what global variables are you referring to?

jesseb07 64 Junior Poster

Obviously I could have run this myself in a compiler but that would have just given me the answer. I need to understand how the loop works so when I face this question in a written exam with different values I can work it out. Thank you for your answers but please realise that just because things seem simple to you guys, they are a little confusing to us beginners. So pointless responses like that from Stinomus are very unhelpful.

'unhelpful' responses usually result from misunderstanding what's being asked.... Anyway, if you were trying to get down what 'for' loops do, this tutorial looked decent:

http://www.hitmill.com/programming/cpp/forLoop.htm

if that's not to your liking I'm sure google has some alternatives.

If you already understand for loops and just want to know how to run through one in your head here's what I do : take it one step at a time and focus on the variable of interest (in this case 'k'). Keep track of what value is being held at 'k' at each step (don't jump around) as you run through your loop (use a piece of paper at first if that's helpful).

if you have a good debugger (I personally have found a liking to VS2008) that could help you see what's going on in a for loop if you set breakpoints throughout it. Doing that for one might clear up on how it actually loops through the block of code (enabling you to …

jesseb07 64 Junior Poster

check my last post, looks like you overlooked it.....

Here are things to help us solve issues with people's programs:
- Sample input/output (none provided)
- Desired input/output (none provided)
- Compiler output (none provided)

There is no reason that I should have to compile your code to find out what the compiler errors are...

I agree, essentially it's good practice (in my opinion) to make it as convenient as possible to help you. Please post the actual and desired input/output.

jesseb07 64 Junior Poster

I see a problem from how the program should be running (although desired results would be nice to know...) it's in your do-while loop
Here's Dave's wonderfully simplified code:

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;
int main ()
{
	int num;
	do
	{
		cout<< "something" <<endl;
		cin>>num;
		cout<<endl;
		num++
	
	}while(num!=0);

	switch (num)
	{

		case (0):
			cout << "End of program"<<endl;
		case (1):
			cout<<"something else"<<endl; 
			break;
		default:
			cout<<"Invalid number. Please choose again.";
			break;	
	}
	return 0;
}

you will notice that the only value of num that will ever get to the switch is 0. Simple fix, move the do-while to include the switch statement:

#include <iostream>
#include <fstream>
#include <cstdlib>

using namespace std;
int main ()
{
	int num;
	do
	{
		cout<< "something" <<endl;
		cin>>num;
		cout<<endl;	

	        switch (num)
	        {

		        case (0):
			        cout << "End of program"<<endl;
                                break;
		        case (1):
			        cout<<"something else"<<endl; 
			        break;
		        default:
			        cout<<"Invalid number. Please choose again.";
			        break;	
	        }
        }
        while(num != 0);

	return 0;
}

see if that's what you're looking to do.

jesseb07 64 Junior Poster

so, does that solve your problem or (since you never said what the problem was) is there more?

jesseb07 64 Junior Poster

Didn't help a bit.

touche ;)

to the OP: indenting your code also makes it easier to follow/read/understand/etc.

jesseb07 64 Junior Poster

code tags really help :)

std::cout << "k: " << k;

or it's really simple to run through that loop in your head... and if you understand what's going on it's even easier to know what the answer is without having to go through the whole loop.

jesseb07 64 Junior Poster

thanks for the responses

That's because you didn't read (or didn't understand) what was said in this link:
http://www.parashift.com/c++-faq-lite/templates.html#faq-35.12

thanks for the link sid, here's my understanding of those articles: I should either live with it or use a compiler that supports "export"?

I'll leave that one where it lies :)

As for the suggestions, adding the cpp file contents into the header worked perfectly, thank you. I guess I was too used to splitting everything into 2 parts.;)

~J

jesseb07 64 Junior Poster

ok, I don't know how I'd do it any differently, but here's a chuck of my structure (it's a modified doubly linked list). None of the functions do anything but move the data around and stores it (ie. I don't do T.c_str() or anything like that)

#pragma once
#include "cell.h"

template <class T> class Row
{
	private:
		unsigned int size;
		Cell<T> *firstCell, *lastCell;
		Row<T> *nextRow, *currentRow, *prevRow;

	public:
		Row();
		~Row();

		T& operator [] (unsigned int index);
		Cell<T>& operator () (unsigned int index);
		void operator = (Row<T> &value);

		void Clear();
		void AddCell(T newValue, unsigned int position);
		//other functions and accessors
};

So that's a small part of the class, as for how I use it that requires specialization, any instance of a different data type requires an explicit specialization, for example:

#include "row.h"
#include "classification.h"
#include "main.h"
using std::string;

//functions etc

function test()
{
          Row<Classification> newNodeValue, tempNodeValue;
          Row<double> coefficients1, coefficients2;
          Row<string> sectionValues1, sectionValues2;

          //blah blah blah
}

this compiles fine but gives linker errors until I include all of the following in "row.cpp"

template class Row<std::string>;
template class Row<Classification>;
template class Row<double>;

I hope I understood correctly what you were asking for.

jesseb07 64 Junior Poster

ah, well if it's still confusing I'll state the question how I would have stated it originally. I just found my original questions in my posts have gotten bloated if I include too much. anyway, maybe 'export' is still what I was looking for, it seemed to be that way from the link, but maybe not if my question was misunderstood. Condensed version:

I have this:

//structure.h
template <class T> class Structure
{
	//stuff goes here
};

//structure.cpp
#include "structure.h"
//functions etc
template class Structure<std::string>;
template class Structure<double>;
template class Structure<unsigned int>; //dont want these

Whenever I use this structure in a new program, I usually need it for a different type (say, char) which means I need to go back to "structure.cpp" and add "template class Structure<char>;". But if it's a non-standard class (say, Shapes) not only do I need to add "template class Structure<Shapes>;" to "structure.cpp" I have to link the objects that have "Shapes" in it (add '#include "shapes.h"' to "structure.cpp"). As you can see it would quickly get tiresome.

Hopefully that cleared up the question, if 'export' is still the answer, ok; but I figure it's worth a shot clarifying.

Thanks!
~J

jesseb07 64 Junior Poster

thanks for the link sid, here's my understanding of those articles: I should either live with it or use a compiler that supports "export"?

thanks to microsoft: http://msdn.microsoft.com/en-us/library/4w5cfxs1.aspx

so am I stuck? how is this accomplished with the standard containers then?

stinomus: I apologize if you misunderstood what I was asking. Give the following a try:

create a separate .cpp and header file of your template class, compile it into an object and try linking that to the object where you give your declaration (if you do that stuff manually) or just build it in VS. Example:

//container.h
template <class T>
class Container
{
  Container(T _data){ data = _data; }
  ~Container(){}
  T data;
};

//container.cpp
#include "container.h"
//functions etc
//make sure you don't put explicit specializations in here, that'd be cheating!

//main.cpp
#include "container.h"

Container<std::string> stringContainer;
//etc.

you will get linker errors and then you will understand what the problem is.

~J

jesseb07 64 Junior Poster

hey, got a quick question regarding template classes. I've made several data structures that I've found to be very useful (using template classes) but it's getting tiresome making a new explicit specialization every time I implement it in a new way. Such as if I want to do this in one of my programs:

Structure<std::string> temp;

I need to have this in the data structure .cpp file

template class Structure<std::string>;

Is there any way to avoid having to do this (the explicit specialization)? The standard containers (vectors, lists, etc) have this ability, I just couldn't find anywhere where it said how to do it. Thanks!

~J

jesseb07 64 Junior Poster

that is my most recent effort, and it does solve the problems with the destructor, but it obliterates the readability of the code (at least with my current function naming convention). Especially since many of my functions take ~4 arguments already. I was going to continue with that method unless someone here thought of a better way to do it that would stick closer to the methods of dealing with standard data structures.

Thanks AD, I'll leave this open for a bit more in case someone else has an idea, but I'll close it soon since we've come to the same conclusion independently.

~J

jesseb07 64 Junior Poster

any ideas? I tried to be as clear as possible, but I understand if my question was lost in the pretext, so I'll see if I can straighten things out.

In my functions I create a List<T> that gets filled with data but when I try to return that list, I get runtime errors from my pointers in the data structure. Here's what I think is happening:

say I try to return a List of type int ( 'List<int> integers' we'll call it) I think that the data in it gets destroyed in the moving between functions

List<int> integers:
size = 5;
nextRow = NULL;
firstCell = 0x0abc0 //Cell object holds pointer for each subsequent cell

when I say "return integers" I think a temporary variable (call it 'tempIntegers') gets created that hold the values of 'integers'

List<int> tempIntegers
size = 5;
nextRow = NULL;
firstCell = 0x0abc0

then since 'integers' was created inside the function, c++ calls 'integers' destructor since it left it's scope. ~List() deallocates all it's cells etc. so now when 'tempIntegers' is passed back here's what it has:

List<int> tempIntegers
size = 5; //should be 0 since all cells were destroyed
nextRow = NULL;
firstCell = 0x0abc0; //has been deallocated by 'integers' destructor

this causes errors as you can imagine if I try to loop through it's elements since the pointers no longer point to memory alloted to my …

jesseb07 64 Junior Poster

hey, I got a question regarding functions returning a linked list. Here's the data structure of my linked list (just in case it deviates from the standard way of doing it)

template <class T> class Link
{
	private:
		unsigned int size;
		Link<T> *nextRow;
		Cell<T> *firstCell;

	public:
		Link();
               ~Link();

		//functions
};

So each Link only consists of it's size, a pointer to the next link, and a pointer to the link's first cell, here is what the problem is I believe. If I have a function that returns say a Link<std::string>, naturally it only returns the Link element (as far as I can tell). I get an access violation if I do something along the lines of this:

Link<std::string> filled;
//fill filled with data

Link<std::string> link = TransferLink(filled);

//other file
template <class T> Link<T> Link<T>::TransferLink(Link<T> start)
{
          Link<T> temp = start;
          return temp;
}

Please note I do have '=' overloaded for Link, but I used this to isolate the problem of transferring the data between functions. What I think happens is c++ makes a temporary variable holding the value of "temp" calls the destructor on the actual variable "temp" and then sends the temporary variable to the "=" assignment. This would explain the access violation since calling the destructor on "temp" would destroy all of the cells in it, but it wouldn't update the size or the pointers of the temporary variable. That's just my thought on what happens. I have gotten it to work by doing the …

jesseb07 64 Junior Poster

Thanks for the help. In my defense my copy-paste is broken so I was typing my code here by hand, which is why I said

Link<int> *test3 = new Link<int>();
delete *test3; //doh error

was a linker error when it should have been (and is)

Link<int> *test3 = new Link<int>(); //linker error
delete test3;

my mistake :P

~J

jesseb07 64 Junior Poster

that fixed it, thanks. This is the first time I've used template classes in C++, so I have to create an explicit declaration for each variant of the class? I'm used to the C# way of doing templates where the compiler does all that for me.

So, say I wanted to be able to have a Link of types int, double, long, and string, I'd need to include all of this at the bottom?

template class Link<int>;
template class Link<double>;
template class Link<long>;
template class Link<string>;

~J

jesseb07 64 Junior Poster

hello, quick question regarding template classes and pointers. I'm making a linked list kind of container system, and I'm running into trouble with it when I (don't know if the terminology is 100% correct here) declare an instance of it. An example would be best to explain what's happening:

I tried the following just to see if it would work ok, on one I get linker issues, on the other, it's fine.

Link<int> test1; //linker error

Link<int> test2(); //compiles fine

Link<int> *test3 = new Link<int>(); //linker error
delete *test3;

Is there something special I need to do to a class to make it able to be a pointer? The rest of the data structure follows, it's quite bare at this point. Thanks!

~J

//link.cpp
#include "link.h"

template <class T>
Link<T>::Link()
{
	size = -1;
	nextLink = NULL;
}

//link.h
template <class T>
class Link
{
	private:
		Link<T> *nextLink;
		int size;

	public:
		Link();
};