Labdabeta 182 Posting Pro in Training Featured Poster

I am using code::blocks and have written a dll. I am currently testing it but am getting tired of having to compile it, copy the DLL, DEF, H and A files into a test project, and then compiling the test project every time I need to fix something. Is there any easier way to test a DLL?

Labdabeta 182 Posting Pro in Training Featured Poster

I was just looking around the web and it looked like this would be a valid solution... is it?

DLL_EXPORT GLOBAL_STRUCTURE globals; //in the above code

Labdabeta 182 Posting Pro in Training Featured Poster

Wow... that was not supposed to happen, I just hit ENTER and it saved. Oh well, this is what I meant to post:

myDLL.h:

#ifndef MYDLL_H
#define MYDLL_H

#ifdef BUILD_DLL
    #define DLL_EXPORT __declspec(dllexport) __stdcall
#else
    #define DLL_EXPORT __declspec(dllimport) __stdcall
#endif
struct GLOBAL_STRUCTURE
{
    int globalInt;
};
#ifndef THIS_IS_MAIN_CPP
    GLOBAL_STRUCTURE globals;
#endif
DLL_EXPORT void initG(GLOBAL_STRUCTURE *gs);
void init(){initG(&globals);}
DLL_EXPORT void myFunctionG(GLOBAL_STRUCTURE *gs);
void myFunction(){myFunctionG(&globals);}
DLL_EXPORT int *getIntG(GLOBAL_STRUCTURE *gs);
void getInt(){return getIntG(&globals);}
#endif

myDLL.cpp

#define THIS_IS_MAIN_CPP
#include "myDLL.h"
DLL_EXPORT void initG(GLOBAL_STRUCTURE *gs)
{
    gs->globalInt=0;
}
DLL_EXPORT void myFunctionG(GLOBAL_STRUCTURE *gs)
{
    gs->globalInt++;
}
DLL_EXPORT void getIntG(GLOBAL_STRUCTURE *gs)
{
    return &(gs->globalInt);
}

My question is whether or not this will work, and if it does work is it safe? Also how c compatible is it?

Labdabeta 182 Posting Pro in Training Featured Poster

No it shouldnt, otherwise i would have to compile with DLL_EXPORT and then change it all to DLL_IMPORT when I want to use it. DLL_EXPORT and DLL_IMPORT are merely macros. Anyways, I am using a pseudo-solution to my problem:

myDLL.h:
#ifndef MYDLL_H#define MYDLL_H#ifdef BUILD_DLL#define DLL_EXPORT __declspec(dllexport) __stdcall#else#define DLL_EXPORT __declspec(dllimport) __stdcall#endifint globalVar;DLL_EXPORT void init();DLL_EXPORT void myFunction();#endif

Labdabeta 182 Posting Pro in Training Featured Poster

I figured it out, but now I cannot find a solution. The problem was that they were global in the header file for a DLL, the main.cpp for compiling the DLL uses extern TYPE VARIABLE_NAME; throughout, whereas when any other main.cpp uses the header file it uses TYPE VARIABLE_NAME. The thing is that I absolutely need globals to be used. Is there any way to use globals in a DLL? EG:

myDLL.h:

#ifndef MYDLL_H
#define MYDLL_H
#ifdef BUILD_DLL
#define DLL_EXPORT __declspec(dllexport) __stdcall
#else
#define DLL_EXPORT __declspec(dllimport) __stdcall
#endif
int globalVar;
DLL_EXPORT void init();
DLL_EXPORT void myFunction();
#endif

myDLL.cpp:

#include "myDLL.h"
DLL_EXPORT void init()
{
    globalVar=0;
}
DLL_EXPORT void myFunction()
{
    globalVar++;
}

main.cpp:

#include "myDLL.h"
int main()
{
    init();
    myFunction();
    return globalVar;
}
Labdabeta 182 Posting Pro in Training Featured Poster

I think this is what you are looking for:

template <typename T>//allow for any type of node
class LinkedListNode
{
    private:
    T value;                    //store the value
    LinkedListNode<T> *next;    //store a pointer to the next node
    LinkedListNode<T> *prev;    //store a pointer to the previous node
    public:
    //getters:
    T getVal(){return value;}
    LinkedListNode<T> &getNext(){return *next;}
    LinkedListNode<T> &getPrev(){return *prev;}
    //setters:
    LinkedListNode<T> &setVal(const T &val){value=val;return *this;}
    LinkedListNode<T> &setNext(LinkedListNode<T> *n){next=n;return *this;}
    LinkedListNode<T> &setPrev(LinkedListNode<T> *p){prev=p;return *this;}
};
template <typename T>//allow for any type of list
class LinkedList
{
    private:
    LinkedListNode<T> *nodes;   //store all the nodes
    size_t numNodes;            //store the total number of nodes
    public:
    LinkedList()
    {
        nodes=NULL;
        numNodes=0;
    }
    LinkedListNode<T> &operator[](size_t index)
    {
        if (index>numNodes)//no need to check lower bound, size_t is unsigned
            exit(1);//or abort in some other way (throw an error if you're into that)
        return nodes[index];
    }
    LinkedList<T> &push(const T &val)
    {
        //the following is just standard dynamic memory management
        LinkedListNode<T> *tmpNodes=new LinkedListNode<T>[numNodes+1];
        for (size_t i=0; i<numNodes; ++i)
            tmpNodes[i]=nodes[i];
        if (numNodes>1)
        {
            tmpNodes[numNodes-1].setNext(&tmpNodes[numNodes]);
            tmpNodes[numNodes].setPrev(tmpNodes[numNodes-1]).setNext(NULL).setVal(val);
        }
        else
            tmpNodes[numNodes].setPrev(NULL).setNext(NULL).setVal(val);
        if (numNodes>0)
            delete[]nodes;
        nodes=tmpNodes;
        numNodes++;
        return *this;
    }
    LinkedList<T> &pop()
    {
        if (numNodes==0)
            exit(1);//or abort in some other way
        //the following is just standard dynamic memory management
        LinkedListNode<T> *tmpNodes=new LinkedListNode<T>[numNodes-1];
        for (size_t i=0; i<numNodes-1; ++i)
            tmpNodes[i]=nodes[i];
        delete[]nodes;
        tmpNodes[numNodes-1].setNext(NULL);
        nodes=tmpNodes;
        numNodes--;
        return *this;
    }
};

Basically the pointers store the access to the next and previous elements in the array. The second struct manages the nodes, setting the pointers, dynamic memory allocation, etc. You should of course add more functionality to the second struct (or in this case …

Labdabeta 182 Posting Pro in Training Featured Poster

I have header guards in the files. So that is not the problem :(

Labdabeta 182 Posting Pro in Training Featured Poster

I told you! Remove the for loop inside the if statement on line 13-14 and replace it with sentence[i]=sentence1[i] Seeing as both WaltP and I explained fairly clearly what was wrong I feel like the code you posted may not have been your own.

Labdabeta 182 Posting Pro in Training Featured Poster

The problem is at line 14. Using that loop is an issue. It should just be:

sencence[i]=sentence1[i];

Here is why. Take the sentence "The cow moved." Lets debug the code.
At i=0: T isalnum=true, sentence1 is copied from 0 to i(0) into sentence, sentence="T"
At i=1: h isalnum=true, sentence1 is copied from 0 to i(1) into sentence, sentence="Th"
At i=2: e isalnum=true, sentence1 is copied from 0 to i(2) into sentence, sentence="The"
At i=3: isalnum=false,sentence1 is not copied at all, sentence="The"
At i=4: c isalnum=true, sentence1 is copied from 0 to i(4) into sentence, sentence="The c" This is where the error occurs.

Labdabeta 182 Posting Pro in Training Featured Poster

I am having a linker error in a file of some 3000 lines that I cannot seem to reproduce. I was wondering if anybody had any ideas where the problem could be. Basically I have a function in a header file and whenever I go to link my project it says:

file:               line:   Message:
main.o                      In function 'myFunction@16':
main.h              123     multiple definition of 'myFunction@16'
main.h              123     first defined here

To me this seems iffy at best! What is going on?!

Labdabeta 182 Posting Pro in Training Featured Poster

Thank you!

Labdabeta 182 Posting Pro in Training Featured Poster

I am having trouble reading your code, but I understand the difficulty in the new system. To start a code block simply skip a line and indent by for. As such
this does not work, even though as I type it it is highlighted like code, it will not show up as code because I didn't leave an empty line.

Leaving a space like the one above then four spaces gets us:

test test :)
Labdabeta 182 Posting Pro in Training Featured Poster

The problem is (as far as I can tell) that you are getting caught by garbage cleanup of some kind. You created an A but it doesnt have a memory space (since new didnt return one) as such when the program ends the operating system tries to automatically destroy a, by calling a default destructor on it that it defined itself. Since A contains two integers, the destructor probably automatically deletes them. The issue is that there is no a to destroy because new never returned one. As such an attempt to delete A results in a crash. Also new returns a pointer and is meant to be used on pointers. Here is an example:

A a();//construct a 'real' A
A *newA=new A;//construct a 'pointer' A

Of course I have been know to be completely wrong before, but I think I am more than less correct this time. :P

Labdabeta 182 Posting Pro in Training Featured Poster

I never knew that near and far were reserved until I made a struct for bounding boxes like this:

struct boundingBox
{
    float near,  far;
    float left,right;
    float top,bottom;
};

Does anybody know what near and far do, because I got the error that the declaration does not declare anything. I solved my problem with a simple rename, but I was also wondering if there was a way to 'turn off' near and far being reserved. My struct is now this in case you are wondering:

struct boundingBox
{
    float front,back;
    float left,right;
    float top,bottom;
};
Labdabeta 182 Posting Pro in Training Featured Poster

I know that OpenGL has special ways to render the teapon, but I want to test my collision detection and scaling algorithms on it, which requires that I have vertices of triangles.

Labdabeta 182 Posting Pro in Training Featured Poster

I want to test some graphics work I am doing with the Utah Teapot model. The issue is that all the data I can find on it uses bezier patches (which I have no clue how to render) does anybody know how I could get the data in a form similar to this:

triangle 1: {x1,y1,z1},{x2,y2,z2},{x3,y3,z3}
triangle 2: {x1,y1,z1},{x2,y2,z2},{x3,y3,z3}
Et cetera, Et cetera
Labdabeta 182 Posting Pro in Training Featured Poster

This link (and the downloadable example) helped me understand rotation in OpenGL far better.

Labdabeta 182 Posting Pro in Training Featured Poster

I want to find a range of values that a valid pointer cannot achieve, but can store. Basically this is my situation:

 typedef struct myNumberTAG
 {
     //stuff
 }*myNumberHANDLE;

 //A bunch of functions that work with myNumberHANDLEs:
 ///Not Shown
 //Some constants
 const myNumberHANDLE numberOne=0x1;
 const myNumberHANDLE numberTwo=0x2;
 const myNumberHANDLE numberInfinity=0x3;
 const myNumberHANDLE numberUndefined=0x4;
 const myNumberHANDLE notAnumber=0x5;

My question is will this work? And if so, what range of values would be viable?

Labdabeta 182 Posting Pro in Training Featured Poster

Check out this site.

Labdabeta 182 Posting Pro in Training Featured Poster

I think that what sergent may be getting at is the idea of a more event-driven programming structure for games. I myself also made a working console snake game (I used colour, variable snake length, and extended ASCII to make it look good :P) and found that having code in this format helps:

#define WINDOW_HEIGHT //define a number here
#define WINDOW_WIDTH  //define a number here too
enum Direction{UP,DOWN,LEFT,RIGHT,NOT};
class Serpent
{
    private:
    Direction dir;
    int length;
    int *x;//array
    int *y;//array
    public:
    //I will just show you the functions, it is up to you to fill them in!
    Serpent();
    void Draw(unsigned char grid[WINDOW_HEIGHT][WINDOW_WIDTH]);//print the snake to the given grid
    void Move(Direction newDir);//rotate the snake in the given direction and move along its path by one (hint: shift your array elements!)
    bool Collision(int X, int Y);//return true if the snake collides with an object at X,Y (basically test if (X,Y) falls in your (x,y) array
    void Extend();//add a new segment to the tail (it should be a doubled value of the x,y coords of the very back of the tail
    bool Check();//return true if gameOver
    int getLength();
}

Once you have that class you can make one like this:

class Board
{
    private:
    unsigned char grid[WINDOW_HEIGHT][WINDOW_WIDTH];
    Serpent s;
    int *badX;//array of bad things (obstacles?)!
    int *badY;//array of bad things (obstacles?)!
    int goodX;//x-coord of the 1-up
    int goodY;//y-coord of the 1-up
    public:
    Board();//initialize the board
    int Step();//return 0 if the game continues, or score
};

Then main can look like this:

Labdabeta 182 Posting Pro in Training Featured Poster

I currently have the following code for a sprite struct (c-style for use in DLL):

typedef struct LABglSpriteTAG
{
    unsigned int glTexture;
    int w;
    int h;
    LABglColour *data;
    bool compiled;
}*LABglSpriteHANDLE;

And the following function:

void LABglSpriteConvolute(LABglSpriteHANDLE spr, int w, int h, int *kernel)
{
    size_t dim=spr->w*spr->h;
    LABglColour *out=new LABglColour[dim];
    for (size_t i=0; i<dim; ++i)
        out[i]=0;
    int centerx=w/2;
    int centery=h/2;
    for (int x=0; x<spr->w; ++x)
    {
        for (int y=0; y<spr->h; ++i)
        {
            for (int kx=0; kx<w; ++kx)
            {
                int xx=w-1-kx;
                for (int ky=0; ky<h; ++ky)
                {
                    int yy=h-1-ky;
                    int rx=x+(kx-centerx);
                    int ry=y+(ky-centery);
                    if (rx>=0&&rx<spr->w&&ry>=0&&ry<spr->h)
                        out[y*spr->w+x]+=spr->data[ry*spr->w+rx]*(1.0/kernel[ky*w+kx]);
                }
            }
        }
    }
    delete[]spr->data;
    spr->data=out;
    #warning SLOW 2012-03-27-12.34: Unknown solution
}

The problem is that this will run in O(nk) time (n being array size, k being kernel size) and takes up a lot of space. Is there any way to optimize this function?

Labdabeta 182 Posting Pro in Training Featured Poster

Sorry, I am still getting used to the new posting system, I guess I didn't do the code right. I cannot seem to figure out how to edit it either.

Labdabeta 182 Posting Pro in Training Featured Poster

Can you maybe post what your iniMatrix class looks like? Also just to maybe catch any premature problems here is some sample vector of vector code:

vector<vector<type> /*note the space that must be here*/> vec;
vector<type> newVec;//this can be set to actually hold something;
vec.push_back(newVec);
vector<type> backVec=vec.back();//this will return the whole vector
///Fake 1D version (in a class)
template<typename T>
class vec2D
{
    private:
    vector<T> vec;
    int w;
    T zero;//this is the default vector value
    public:
    vec2D(int h, int w, int v):w(w),zero(v)
    {
        for (int i=0; i<w*h; ++i)//set the vector to {v}
            vec.push_back(v);
    }
    T &operator()(int x, int y)
    {
        if (x*y>=vec.size())
        {
            //we need to reserve more space!
            if (x>w)
            {
                for (int xx=0; xx<x; ++xx)
                {
                    for (int i=0; i<vec.size()/w; ++i)
                        vec.insert(vec.begin()+i*w,zero);
                    w=x;
                }
            }
            if (y>vec.size()/w)
            {
                for (int yy=0; yy<y; ++yy)
                {
                    for (int i=0; i<w; ++i)
                        vec.push_back(zero);
                }
            }
        }
        return vec[y*w+x];
    }
};

NOTE: I may have made a mistake with my class and it could definately use some more functionality, it is merely for showing you how you COULD make a fake 2D-vector class.

Labdabeta 182 Posting Pro in Training Featured Poster

I have tried framebuffers and can never get them to work. I have tried many different versions of test code for them and every single one either fails to compile or fails to link. Could you maybe post source code for a test example? Also I was wondering if, since I am using windows API to begin with, I can use some Windows API function to blit a texture (I do have the data stored in a variable along with its openGL texture index).

Labdabeta 182 Posting Pro in Training Featured Poster

My internet explorer still will not allow me to reply, but I do prefer Firefox so I am using it. I think I need a tech upgrade though (from my Dell Latitude D630) because even cmd is lagging occasionally (I have run diagnostics, and malwarebytes anti malware to check for problems, both saying that everything is A-Okay). Luckily I graduate from high-school in a few months and will be getting a really awesome custom desktop computer for university. For now I will just use firefox and bear with the lag for just a few more months. Thank you.

Labdabeta 182 Posting Pro in Training Featured Poster

I am sorry to have to make a new thread for this, but as I cannot reply to any threads I cannot think of another easy option. Basically when I enter my message and click the submit button, a red box shows up and says "Message field required" How can I reply?

Labdabeta 182 Posting Pro in Training Featured Poster

I am wondering how to perform a 2D image blit with openGL. I used to use SDL and it was easy, but with opengl I end up making a rectangle with texture coords that is sunk a little into the screen. Is there any way to perform a 'real' blit?

void blitImage(unsigned int glTex, int top, int left)
{
    //what do I do?
}
Labdabeta 182 Posting Pro in Training Featured Poster

I am not an expert, as I only recently started learning opengl myself, but from my understanding glLoadIdentity() clears the currently selected matrix. If you read through the OpenGL Documentation thoroughly, you will find that OpenGL stores four matrices of data. I learnt about them from a very helpful tutorial here. Basically the first matrix is the model matrix, it stores the offsets for the creation of stuff in your scene. The second matrix is the view matrix, it stores the offsets for the camera that views your scene. The third matrix is the modelview matrix, which is a combination of the two. The final matrix is the projection matrix, which stores information about how the camera draws the scene. Calling glLoadIdentity() resets the currently loaded matrix to an empty array (of zeroes if I remember correctly) allowing you to transform the matrices without just adding onto the previous transformations.

Labdabeta 182 Posting Pro in Training Featured Poster

I would suggest debugging your code. You can then see where you go wrong. There are many mistakes regarding arrays, I would suggest you read some material on how they work. Also, your swap function does no sorting at all. In fact I don't think it even swaps the data, though I have not tested it. You need to look up sorting algorithms and find one that is easy enough to implement and yet fits your problem.

Labdabeta 182 Posting Pro in Training Featured Poster

Based on what I read, it seems as though the general technique is to sort the objects by proximity to the object being sorted and then starting at the start of the sorted array, check bounding boxes, then if a bounding box intersects check precise collision. I will now implement that. Thank you very much!

Labdabeta 182 Posting Pro in Training Featured Poster

Thank you very much... I am wondering what you mean by collision detection algorithm. I am using a ton of math for point-by-point collision detection (using triangle-ray collision algorithms) and very little math for bounding box collisions (obviously). I have no pruning implemented as I do not know of any pruning algorithms... does anybody have any suggestions on good algorithms to help speed up my collision detection?

Labdabeta 182 Posting Pro in Training Featured Poster

I am working on a game making (or really just general program making, but my question applies to games) DLL for opengl. It is almost done but the collision detection is a little bit slow since it has to calculate bounding boxes for each object repeatedly. I was thinking of storing six extra variables for each object (left,right,top,bottom,near,far) to remove the need for those calculations. The thing is that that will add (c++ code, compiler dependant) 6*sizeof(float) bytes to each object. My question is, on average how many objects do most games have in them (an object consisting of a list of triangles in 3d space that are bound together), and how much RAM taken is too much? Basically should I add the six variables to increase speed but increase memory, or not?

Labdabeta 182 Posting Pro in Training Featured Poster

Also shouldn't you use some kind of heuristic algorithm for making the computer play. You can do it with simple if statements and loops, or if you up for a challenge a minimax algorithm with alpha beta pruning allows for a variable AI.

Labdabeta 182 Posting Pro in Training Featured Poster

The derivative will not be a single integer, I think you want the value of the derivative at a specific point, in that case you will need to be given the point (x). Also, how are you supposed to know how long the array is if you don't pass a dimension? I would suggest something like this:

int * differentiate(int [] coefficients, int numCoefficients)
{
    int *ret=new int[numCoefficients];
    for (int i=0; i<numCoefficients; ++i)
        //recalculate coefficients and put them in ret here
    return ret;
}
int differential(int coefficients[], int numCoefficients, int x)
{
    int ret=0;
    for (int i=0; i<numCoefficients; ++i)
        ret+=x*i*pow(coefficients[i],i-1);
    return ret;
}
Labdabeta 182 Posting Pro in Training Featured Poster

I do not know of any resources off hand, but I used to use GML's automatic collision detection and it gave a half-decent explanations in the help files. It said that it starts by checking a bounding box defined by the most extreme points on the image. A bounding box is easy to check collision for:

bool isInBox(float x, float f, float boxTop, float boxLeft, float boxBottom, float boxRight)
{
    return ((x<=boxRight&&x>=boxLeft)&&(y<=boxBottom&&y>=boxTop));
}

If that returns true you have to decide whether you want to continue checking. If you do want to continue checking you will have to break the image into a bunch of rectangles and check them. I believe there are algorithms out there that can break the image into rectangles, I just don't know any off hand.

Labdabeta 182 Posting Pro in Training Featured Poster

I haven't read all your code... but why in your record structure do you declare a bunch of string arrays of size true (1)?

Labdabeta 182 Posting Pro in Training Featured Poster

I was introduced to programming four years ago in grade nine BTT10 Tech class. For about 95% of the year we just worked with the microsoft office suite, but for about a week or two we made small games using gamemaker. I was already a gamer and went overboard with my game, introducing code where everybody else was just using the drag and drop features. I found that I loved programming and ended up using a gamemaker wiki which has since been taken down to learn about the inner workings of gamemaker. When I found myself restricted by gamemaker's strict event driven programming and extremely slow load time (every game you make can take upwards of a minute to initialize) I decided to research what language would be fastest and best for game making. I had heard about c++ and looked into it. I followed all of the tutorials on learncpp.com, then all the tutorials on Lazyfoo, then all of the tutorials on a windows console tutorial which too has been taken down, and now I am working my way through NeHe.

Labdabeta 182 Posting Pro in Training Featured Poster

Not to stick my head in where it doesnt belong, but if a student is having trouble understanding a concept and their teacher is unable to get them to explain it are they not allowed to do research? And when that research comes up fruitless are they not allowed to ask for guidance from others? It is clear that the student made an effort to solve the homework on their own, but needed some help. Homework should be assigned to help students learn, if they learn then it should matter very little how they got their solutions. I understand discouraging the using of forums to get answers, but to help understand answers I think that they can be helpful. It seems as though there was a student who did not understand bubblesorting of strings who now understands bubblesorting of strings. Furthermore by definition a student must study, if something is preventing them from being able to study then any good student should seek to rectify it. If a student has made a legitimate effort to solve a problem and has been unable to come up with a solution due to lack of understanding then they should be allowed to use almost any means by which to understand, assuming they are not being assessed. Of course if this was not 'homework' per se, but rather an assignment I take back what I have said and completely understand your concerns. Finally I also hope that the student will/did not plagiarize from the …

Labdabeta 182 Posting Pro in Training Featured Poster

To edit you merely overwrite data usually (output the old data, input the new) to delete you usually remove the element by shifting all those after it back by one. I would suggest that an std::vector would be extremely useful in this situation.

Labdabeta 182 Posting Pro in Training Featured Poster

I suppose that was somewhat helpful... although I wish there was a cure-all :( I think I will, at least for the moment, stick to display lists, as they are simpler and my graphics card supports them.

Labdabeta 182 Posting Pro in Training Featured Poster

I recently looked at this description of VBOs and a sample implementation of them. When I ran the executable, it was significantly faster with no VBOs than with them. I don't understand why it should be slower with the VBOs than without. Can anybody explain why?

Labdabeta 182 Posting Pro in Training Featured Poster

If sort works then you should have no trouble with sort2. In fact please delete sort2. The thing you do not seem to realize is that sort and sort2 are EXACTLY the same. Just changing the name of the parameters does not change the function. Here is an example:

void addOne(int &numberOne){numberOne++;}
int main()
{
    int numberOne;
    int numberTwo;
    cin>>numberOne>>numberTwo;
    addOne(numberOne);//okay, we will add one to number one
    addOne(numberTwo);//this is still okay because numberTwo gets sent to the addOne function, which gives it the name numberOne, but just for the duration of the function
    cout<<numberOne<<numberTwo<<endl;
    return 0;
}
Labdabeta 182 Posting Pro in Training Featured Poster

Thank you! I hate it when problems hide away in other functions!

Labdabeta 182 Posting Pro in Training Featured Poster

I have gotten my debugger to work and have a nearly perfect program working. The problem now is a single stray character at the end (I believe it has an ASCII value of -cENDL) here is the new code:

#include <iostream>     //for cin/cout
#include <string>       //for std::strings, obviously
#include <fstream>      //for file operations
#include <stdio.h>      //for integer parsing
using namespace std;
string readFile(string fileName)
{
    fstream file(fileName.c_str()); //open the file
    if (!file.is_open())            //check that it opened
        return "";
    string ret="";                  //initialize the return value
    while (!file.eof())             //loop through the whole file
        ret+=file.get();            //grab a character and append it to the return value
    file.close();                   //close the file
    return ret;
}
void writeFile(string fileName, string text)
{
    fstream file(fileName.c_str()); //open the file
    if (!file.is_open())            //check that it opened
        return;
    file<<text;                     //write the text
    file.close();                   //close the file
}
struct highlightFormatter
{
    string start;           //this is written at the start of the information
    string end;             //this is written at the end of the information
    string newLine;         //this is written at the end of each line of the information
    string code;            //this is written at the start of a segment labeled as code
    string comment;         //this is written at the start of a segment labeled as comment
    string documentation;   //this is written at the start of a documentation comment
    string preprocessor;    //this is written at the start of a preprocessor
    string str;             //this is written at the start of a string literal
    string chr;             //this is written at the start of a character …
Labdabeta 182 Posting Pro in Training Featured Poster

That is a lot of code! I have not read over it, but I would suggest that this should work:

int main()
{
    time_t start=time(NULL);//get start time
    //TONS OF TIME CONSUMING CODE!!!
    time_t end=time(NULL);//get end time
    time_t deltatime=start-end;//this now stores how long the code took!
    //output?
    return 0;
}
Labdabeta 182 Posting Pro in Training Featured Poster

Basically my code gets stuck at saying 0% formatted. I did a complete re-do from my previous version, but just for the sake of it here is my previous version:
bettermain.cpp: (not nearly as helpful and painfully difficult to modify, also glitchy)

#include <stdio.h>
#include <string>
using namespace std;
string readFile(string fname)
{
    FILE *file=fopen(fname.c_str(),"r");
    printf("Opening input file...\n");
    if (file==NULL)
        return "";
    string ret="";
    while (!feof(file))
        ret+=fgetc(file);
    fclose(file);
    return ret;
}
void writeFile(string fname, string text)
{
    FILE *file=fopen(fname.c_str(),"w");
    printf("Opening output file...\n");
    if (file==NULL)
        return;
    printf("Printing to file...\n");
    for (int i=0; text[i]; i++)
    {
        fputc(text[i],file);
        printf("%c",text[i]);
    }
    printf("Done printing to file...\n");
    fclose(file);
}
void replaceAll(string &text, char find, string replace)
{
    string ret="";
    for (int i=0; i<(int)text.length(); i++)
    {
        if (text[i]==find)
            ret+=replace;
        else
            ret+=text[i];
    }
    text.swap(ret);
}
int log(int x)
{
    int ret=0;
    while (x>0)
    {
        x/=10;
        ret++;
    }
    return ret;
}
void replaceAllInc(string &text, char find, int startindex)
{
    string ret="";
    int num=startindex;
    for (int i=0; i<(int)text.length(); i++)
    {
        if (text[i]==find)
        {
            char *temp=new char[log(num)+1];
            sprintf(temp,"%i",num++);
            ret+=temp;
            delete[]temp;
        }
        else
        {
            ret+=text[i];
        }
    }
    text.swap(ret);
}
string highlight(string itext)
{
    string keywords[]={
       "asm","auto","bool","break","case","catch",
       "char","class","const","const_cast","continue",
       "default","delete","do","double","dynamic_cast",
       "else","enum","explicit","export","extern",
       "false","float","for","friend","goto","if",
       "inline","int","long","mutable","namespace",
       "new","operator","private","protected","public",
       "register","reinterpret_cast","restrict","return",
       "short","signed","sizeof","static","static_cast",
       "struct","switch","template","this","throw",
       "true","try","typedef","typeid","typename",
       "union","unsigned","using","virtual","void",
       "volatile","while","int8_t","uint8_t","int16_t",
       "uint16_t","int32_t","uint32_t","int64_t","uint64_t",
       "int_least8_t","uint_least8_t","int_least16_t",
       "uint_least16_t","int_least32_t","uint_least32_t",
       "int_least64_t","uint_least64_t","int_fast8_t",
       "uint_fast8_t","int_fast16_t","uint_fast16_t",
       "int_fast32_t","uint_fast32_t","int_fast64_t",
       "uint_fast64_t","intptr_t","uintptr_t","intmax_t",
       "uintmax_t","wint_t","wchar_t","wctrans_t",
       "wctype_t","size_t","time_t","and","and_eq",
       "bitand","bitor","compl","not","not_eq","or",
       "or_eq","xor","xor_eq","complex","imaginary",
       "_Complex","_Imaginary","_Bool","_Pragma","|EOF"
    };
    string dockeywords[]={
        "a", "addindex", "addtogroup", "anchor", "arg", "attention",
        "author", "b", "brief", "bug", "c", "class", "code", "date",
        "def", "defgroup", "deprecated", "dontinclude", "e", "em",
        "endcode", "endhtmlonly", "endif", "endlatexonly", "endlink",
        "endverbatim", "enum", "example", "exception", "f$", "f[", "f]",
        "file", "fn", "hideinitializer", "htmlinclude", "htmlonly", …
Labdabeta 182 Posting Pro in Training Featured Poster

Okay... lets see if we can explain this. Here is a pseudoC++code bubblesort algorithm which I expect you are familiar with:

void bubbleSort(Array X)
{
    bool swapped=true;
    int length=lengthOf(X);
    while (swapped)
    {
        swapped=false;
        for (int i=1; i<length-1; ++i)
        {
            if (X[i-1]>X[i])
            {
                swap(X[i-1],X[i]);
                swapped=true;
            }
        }
        --length;//this is an optimization that can be done
    }
}

Thi issue is that lengthOf(X) is undefined and X[i-1]>X is undefined for strings. The problem then becomes defining these things. To get the length you will likely pass in a parameter called length. For the X[i-1]>X issue you can use strcmp(X[i-1],X). Basically strcmp(A,B) can be thought of as A>B. The thing is that you want to compare more than one string so you need to define an even more complicated comparison algorithm. This is easiest to do if you group all of your strings (city, first, last) into a struct. As such your final code would look something like this:

const int STRING_BUFFER_SIZE=80;//increase this to allow for really long names
struct Individual//this will store 1 person
{
    char firstName[STRING_BUFFER_SIZE];
    char lastName[STRING_BUFFER_SIZE];
    char cityName[STRING_BUFFER_SIZE];
};
//this function will be equivalent to a>b
bool isGreater(Individual a, Individual b)
{
    int result = strcmp(a.cityName, b.cityName);//determine if the cities are different
    if( result != 0 )//if they are then...
        return (result > 0);//return true if city A comes first
    result = strcmp(a.lastName, b.lastName);//cities are the same... check last names
    if( result != 0 )//if they are different
        return (result > 0);//return true if last name A …
Labdabeta 182 Posting Pro in Training Featured Poster

You could make your own version of strcmp. Here is what it could look like:

int strcmp(char *str1, char *str2)
{
    for (int i=0; str1[i]&&str2[i]; ++i)//compare each character
    {
        if (str1[i]>str2[i])
            return 1;
        if (str2[i]>str1[i])
            return -1;
    }
    //so far they are the same.... compare lengths
    int str1len,str2len;
    for (str1len=0; str1[str1len]; ++str1len){}//get str1len
    for (str2len=0; str2[str2len]; ++str2len){}//get str2len
    if (str1len==str2len)
        return 0;//they are the same string
    else if (str1len>str2len)
        return 1;//str1 is bigger
    else
        return -1;//str2 is bigger
Labdabeta 182 Posting Pro in Training Featured Poster

The thing is that you cannot (as far as I know) call main recursively (from within itself) and even if you can it is likely a bad idea (if the user wants to do 100 problems you will outrun your stack) The key is to use a loop. Here is an example for your code:

#include <stdio.h>
#include <conio.h>

main()

{
float choice,A,CUBE;
char temp;
bool exit=false;
while (!exit)//loop until we want to exit
{//I do not know why you put a block here... but I am using it :P
clrscr();
textcolor(BLUE);
gotoxy (24,5);
cprintf("SOLVE FOR THE FOLLOWING VOLUMES\n");
textcolor(345);
gotoxy (26,7);
cprintf("[1]   -    CUBE");
gotoxy (26,8);
cprintf("[2]   -    CONE");
gotoxy (26,9);
cprintf("[3]   -    SPHERE");
gotoxy (26,10);
cprintf("[4]   -    CYLINDER");
gotoxy (26,11);
cprintf("[5]   -    EXIT");
textcolor(RED);
gotoxy (24,14);
cprintf("Enter your choice:   ");
scanf("%f",&choice);

switch(choice)
{
case 1:
  {
    clrscr();
    textcolor (BLUE);
    gotoxy (30,5);
    cprintf("Volume of CUBE");

    textcolor (345);
    gotoxy (24,7);
    cprintf("Enter the side of the cube: ");
    scanf("%f",&A);

    CUBE=  (A*A*A);
    scanf("%2.0f,&CUBE");

    textcolor (345);
    gotoxy (24,10);
    cprintf("The Volume of the CUBE is %2.0f", CUBE);
  }
case 5://you do not NEED blocks after a case statement, but they can make your code look nicer
textcolor (RED);
gotoxy(24,14);
cprintf("Would you like to compute again(Y/N)? ");
scanf("%c", &temp);

exit = (!(temp == 'y' || temp == 'Y'));//set the exit variable
  }//end switch
 }//end while
return 0;
}//indentation would have told you that this bracket ends main
Labdabeta 182 Posting Pro in Training Featured Poster

This program is designed to be run to turn an input file full of c++ code into an output file that contains that code parsed to be highlighted in an HTML document (or any other document for that matter) Basically I need to have it such that I insert strings before every change in syntax highlighting type. Here is another formatters.txt file that, were the program working, would illustrate the point better: (note that #! is parsed as a new line, ## is parsed as an incrementing counter and #X where X is 0-9 is parsed as setting that counter, also the last line is just a list of keywords)

#2START CODE#!(
)#!END CODE#!
)#!LINE # ##:(
)Code(
)Comment(
)DocumentationComment(
)Preprocessor(
)StringLiteral(
)CharacterLiteral(
)Keyword(
)DocumentationCommentKeyword(
)Operator(
)NumericLiteral(
asm auto bool break case catch char class const const_cast continue default delete do double dynamic_cast else enum explicit export extern false float for friend goto if inline int long mutable namespace new operator private protected public register reinterpret_cast restrict return short signed sizeof static static_cast struct switch template this throw true try typedef typeid typename union unsigned using virtual void volatile while int8_t uint8_t int16_t uint16_t int32_t uint32_t int64_t uint64_t int_least8_t uint_least8_t int_least16_t uint_least16_t int_least32_t uint_least32_t int_least64_t uint_least64_t int_fast8_t uint_fast8_t int_fast16_t uint_fast16_t int_fast32_t uint_fast32_t int_fast64_t uint_fast64_t intptr_t uintptr_t intmax_t uintmax_t wint_t wchar_t wctrans_t wctype_t size_t time_t and and_eq bitand bitor compl not not_eq or or_eq xor xor_eq complex imaginary _Complex _Imaginary _Bool _Pragma string wstring NULL

An example run would look …