Labdabeta 182 Posting Pro in Training Featured Poster

I am trying to find a bug in my new and (theoretically) improved syntax highlighter program. I have made 3 versions now and have been able to debug them all with ease. Unfortunately my debugger does not do well with std containers as it shows ALL the information they contain and it can be hard to sift through it to find errors. Can anybody see where I went wrong in this code?

evenBetterMain.cpp: (since I already have main.cpp and betterMain.cpp working :P)

#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; …
Labdabeta 182 Posting Pro in Training Featured Poster

That link gives a good description of covolution in general, which I already know. I want to know how to use an opengl call to glConvolute2D to apply a convolution kernel to the window.

Labdabeta 182 Posting Pro in Training Featured Poster

Okay... thanks for the help. I think that it may not be worth the trouble. My files are only around 50-100k (binary format) and the data is all over the place. I don't think that compression is necessary, though I may revisit the topic later. Thanks for the help.

Labdabeta 182 Posting Pro in Training Featured Poster

Theoretically I could convert the variables to string.... but not very efficiently. I was wondering if there was any kind of online compression algorithm that takes one byte at a time and encrypts it to the file. Something with a function prototype that could look like this:

void writeCompressed(FILE *file, unsigned char byte)
Labdabeta 182 Posting Pro in Training Featured Poster

I don't think you ever made a PLUCode variable. I could be wrong, but it's definition is definately not easy to find.

Labdabeta 182 Posting Pro in Training Featured Poster

Thank you, that was a helpful link, but I don't really think it suits my needs well (I am storing many variables of different types.) I was wondering if there are any on-line (not as in on the internet but as in sequential input) algorithms that compress individual bytes into a file. I just want a very simple algorithm... Assuming one exists.

Labdabeta 182 Posting Pro in Training Featured Poster

First of all you made neither of the changes I suggested, so even after you stop getting errors your code will not work. Second note that you named the function getChangeStock, not changeStock so that is one of your errors.

Labdabeta 182 Posting Pro in Training Featured Poster

That was helpful! I noticed a few things. One, on line 28 I do not think you need to open the file as I think the constructor will have done that for you. The main problem though I believe lies in line 100. You have this inFile and are intending to read from it, but it appears that you accidentally read from cin instead. Change cin>>plu.... to inFile>>plu...

Labdabeta 182 Posting Pro in Training Featured Poster

I understand that data on computers can be compressed (I see it all the time with zip files and jpegs) but I was wondering just how compression works. Thinking it through, if you data is represented by 1s and 0s then it can be corresponded 1 to 1 with a binary number (albeit a large one). The idea behind compression is that some smaller number can represent the same data, but how is this possible since that new number must represent something else? I suppose if you know in advance that this number is a compressed version of another number than you can interpret it differently? Are there any relatively simple compression algorithms?

Labdabeta 182 Posting Pro in Training Featured Poster

Could you post your source? It could be a silly error in the code.

Labdabeta 182 Posting Pro in Training Featured Poster

You have a fair bit of code there... could you use [ CODE ] tags to get it highlighted for us?

Labdabeta 182 Posting Pro in Training Featured Poster

How exactly do you use a glConvolutionFilter2d() call? I know about convolution filters and kernels, but am not sure exactly how to implement them. Just a simple example with say... a gaussian blur, would be helpful.

Labdabeta 182 Posting Pro in Training Featured Poster

This can be easily done with a loop:

int main()
{
    bool exit=false;
    while (!exit)
    {
        //CODE HERE!
        //somewhere have:
        /* if (user_want_to_quit)
                exit=true;
        */
    }
    return 0;
}
Labdabeta 182 Posting Pro in Training Featured Poster

Modularization will be key here. If you have not yet learnt functions, look them up. Then you can make your main look like this:

const int numNames=10;//this helps make the code more flexible
int main()
{
    char name[numNames][80];
    for (int i=0; i<numNames; ++i)//use a loop
        gets(name[i]);
    char firstNames[numNames][80];
    char lastNames[numNames][80];
    char city[numNames][80];
    breakApart(name,firstNames,lastNames,city);//this function will deal with the spaces
    sortNames(city,firstNames,lastNames);
    cout<<"Sorted names:"<<endl;
    for (int i=0; i<numNames; ++i)
    {
        cout<<city[i]<<' '<<firstNames[i]<<' '<<lastNames[i]<<endl;
    }
    return 0;
}

The sorting algorithm can just sort the arry three times (by the different values) since bubble sort is stable. Here is some pseudo-code for that function:

void sortNames(char array1[numNames][80],char array2[numNames][80],char array3[numNames][80])
{
    //bubble sort array3 remembering that any swaps you do you must do to all the arrays
    //bubble sort array2 remembering that any swaps you do you must do to all the arrays
    //bubble sort array1 remembering that any swaps you do you must do to all the arrays
}
Labdabeta 182 Posting Pro in Training Featured Poster

I am not certain, but I do not think that if (opr='+',...) works. I would suggest trying:

if (opr='+'||opr='-'||...)
Labdabeta 182 Posting Pro in Training Featured Poster

Or better yes using an std::vector of std::strings could make life easy-peazy, no?

Labdabeta 182 Posting Pro in Training Featured Poster

For sorting I would suggest looking up sorting algorithms. Once an array is sorted you can use a binary search to find an element.

Labdabeta 182 Posting Pro in Training Featured Poster

After reading it again I guess I don't fully understand the stencil buffer. Is it some kind of storage space on the GPU? How exactly does it work? Could I also implement shadows as a 2D image that I overlay on top of my scene before drawing it? Could I do some math and create a set of triangles that represent the triangle and are placed just above the surfaces on which they are set?

Labdabeta 182 Posting Pro in Training Featured Poster

Thank you, your description helped a bit. I will try to read the tutorial again and see if I can get it working. Ill post back if I need more help.

Labdabeta 182 Posting Pro in Training Featured Poster

How do you make shadows in OpenGL. I have been using the NeHe tutorials, but I do not understand their shadow lesson. Can anybody help?

Labdabeta 182 Posting Pro in Training Featured Poster

I think that the best way to do this is probably through another function definition. Basically you can use your function, but also declare one like this:

DOSTUFF& Insert()
{
    //whatever you do with no parameters
}

I am not sure if it would work, but I would think that the compiler would automatically match Insert() to the void version rather than try to fit the templated version. To check the type I think you can use type_id or something like that, do some research and you should be able to find it... if not I am sure that someone else on this forum knows the answer. To restrict templates to a specific type I refer you to http://www.learncpp.com/cpp-tutorial/146-partial-template-specialization/, it is quite informative. Hope this helps!

Labdabeta 182 Posting Pro in Training Featured Poster

You did not design your functions as well as you could have. That will make it hard. A function should be a single simple task, and it should do the entire task as expected. The function RemoveSpaces() then should probably take a string and... remove all its spaces. A sample implementation could be:

void RemoveSpaces(char *str)//char * is basically the same as char[]
{
    for (int i=0; str[i]; ++i)//loop until we hit the null character (str[i]==0)
    {
        if (str[i]==' ')//its a space!
            str[i]=' '+3;//or whatever you set it to
    }
}

Now if you want to remove spaces from a string you just call RemoveSpaces with the string as its argument. Here is an example:

int main()
{
    char myString[256];
    cout<<"Enter a string!"<<endl;
    cin.ignore();//I think this is needed to get rid of the endl... but I could be wrong
    cin.getline(myString,sizeof(myString));
    RemoveSpaces(myString);
    cout<<"You string without spaces looks like: <<myString<<endl;
    return 0;
}

Of course a better implementation of RemoveSpaces would remove the spaces entirely, leaving no trace that they were there at all. But that would require an extra array and complexity that you do not need right now. Similarly you could write a function like this:

void Encrypt(char *str)
{
    //for the sake of example, this encryption will remove all the spaces
    //  and add 1 to each ASCII value
    RemoveSpaces(str);
    for (int i=0; str[i]; ++i)
        str[i]+=1;
}

The decrypt function that could go along with that could look like this:

void Decrypt(char *str)
{
    for …
Labdabeta 182 Posting Pro in Training Featured Poster

ddanbe caught a mistake of mine, it is de bello gallico. My bad.

Labdabeta 182 Posting Pro in Training Featured Poster

First of all, why make a modulus function. There is a pretty little operator for that in c++ (%). Also I would suggest avoiding infinite loops and relying on the system to stop your program. Instead use a boolean to wait for... what? I have no Idea what the goal is, the program does not make much sense (the variable names are pretty bad). For the matrix letter effect you would need some ability to seek in the console. Then you can do something like this:

class MatrixStreak;
int main()
{
     vector<MatrixStreak> streaks;
     bool continuing=true;
     while (continuing)
     {
         if (randomNumber()==0)
         {
             streaks.add(MatrixStreak();
         }
         for (int i=0; i<streaks.size(); ++i)
         {
             streaks[i].draw();
         }
         continuing=keyIsPressed(ENTER);//or whatever you want
    }
    return 0;
}
class MatrixStreak
{
    private:
    int x,y,ylimit;
    public:
    MatrixStreak()    
    {
        x=randomNumber();
        y=randomNumber();
        ylimit=y+randomNumber();
    }
    bool draw()//return false if dead
    {
        putAt(x,y++,randomCharacter());
        return (y<ylimit);
    }
};

Of course that was just pseudo-code. The necessary functions would be platform specific.

Labdabeta 182 Posting Pro in Training Featured Poster

I have the following collision detection function that checks the collision between the line defined by lstart -> lend and the triangle defined by points a,b and c with a normal of nvec. I want to know if it will work and what to put into the missing part. (it is near the start and is commented). Here is my code:

bool Collides(glCoordFloat lstart,glCoordFloat lend,glCoordFloat a,glCoordFloat b,glCoordFloat c,glCoordFloat nvec)
{
    //calculate the dot product of vec and nvec
    double vn=((lend.x-lstart.x)*nvec.x)+((lend.y-lstart.y)*nvec.y)+((lend.z-lstart.z)*nvec.z);
    if (closeEnough(vn,0))//if this is zero than the line is parallel to the triangle!
    {
        //calculate the dot product of start->a point on the plane of the triangle and nvec
        double dn=((lstart.x-a.x)*nvec.x)+((lstart.y-a.y)*nvec.y)+((lstart.z-a.z)*nvec.z);
        if (closeEnough(dn,0))//it IS in the plane of the triangle!
        {
            //check for intersection of the three lines bounding the triangle and the vector
            //I am stuck...
            return ( )
        }
        else
        {
            //there is absolutely no way that that there is an intersection! GOOD BYE!
            return false;
        }
    }
    //ok, so it has a specific point of intersection with the plane, lets find it
    double s;//s is how far along the vector the intersection is!
    s=((nvec.x*(a.x-lstart.x))+(nvec.y*(a.y-lstart.y))+(nvec.z*(a.z-lstart.z)))/vn;
    if (s<0.0||s>1.0)
    {
        //not in the plane, not in the triangle!
        return false;
    }
    glCoordFloat i;//this is the intersection!
    i.x=lstart.x+vec.x*s;
    i.y=lstart.y+vec.y*s;
    y.z=lstart.z+vec.z*s;
    //now to check if i is in the triangle a,b,c
    //calculate the dot-products:
    double uu=((b.x-a.x)*(b.x-a.x))+((b.y-a.y)*(b.y-a.y))+((b.z-a.z)*(b.z-a.z));
    double vv=((c.x-a.x)*(c.x-a.x))+((c.y-a.y)*(c.y-a.y))+((c.z-a.z)*(c.z-a.z));
    double uv=((b.x-a.x)*(c.x-a.x))+((b.y-a.y)*(c.y-a.y))+((b.z-a.z)*(c.z-a.z));
    double uw=((b.x-a.x)*(i.x-a.x))+((b.y-a.y)*(i.y-a.y))+((b.z-a.z)*(i.z-a.z));
    double vw=((c.x-a.x)*(i.x-a.x))+((c.y-a.y)*(i.y-a.y))+((c.z-a.z)*(i.z-a.z));
    double denom=(uv*uv)-(uu*vv);
    s=((uv*vw)-(vv*uw))/denom;//why re-allocate s?
    if (s<0.0||s>1.0)
    {
        //not in the triangle, sorry :C
        return false;
    } …
Labdabeta 182 Posting Pro in Training Featured Poster

I guess I'll chime in. I always end my emails with "Veni, Vidi, Didici"-(LAMBDA)(ALPHA)(BETA) since my initials are LAB but using λαβ just looks so much cooler. I came up with my slogan last year in latin class while reading De Bella Gallica (On the gallic wars) by Julius Caesar. It is derived from his "Veni, Vidi, Vici" which means "I came, I saw, I conquered" I modified it to "I came, I saw, I learnt". When I was typing in my username to create this account I suppose I missed the 'm' key. Thus labdabeta.

Labdabeta 182 Posting Pro in Training Featured Poster

Thank you, that was very helpful. I am lucky that my story line will help me out greatly. You start in a war zone where you have to help an injured buddy to a large military complex to get him healed. This will help give you that connection with the character that you were talking about. Once you get to the complex there are a few levels where you just get used to the scary environment of the large complex, but there are human allies all around you so you should not be too afraid. Along the way you start hearing that weird stuff is happening outside. When you get to the medical center it blows up and then the horrific zombie attacks start. This post will be VERY helpful to me as a reference for making my map. I might even put you in the credits ;) (I have a clever idea of writing them in blood on the street that you walk out on)

Labdabeta 182 Posting Pro in Training Featured Poster

A few friends and I made a bet to see who could single-handedly (we defined that as a team of up to 10 people, all of whom must be personal friends) make the best video game over the course of two years. I am planning on making a first-person horror game. I have already lined up a storyline, my brother is working on my sprites and 3D models, and a friend of mine is dealing with audio. This leaves me stuck with level design. Does anyone have any tips for how to design good levels? This will be the biggest project I have ever encountered. I have made three 3rd person shooters before (all HUGE hits among my friends) and two 1st person maze games (more of a test of my skills, but still fun to play). Any other tips for making a good game are welcome. I am in grade 12, and will be going into software engineering next year. For now I could really use some help (I am behind in the bet :() Thank you!

Labdabeta 182 Posting Pro in Training Featured Poster

Any array is just a pointer to its first value, followed by allocated memory for the remaining values. As such this will work:

int myArray[]={5,3,6,8,4,2,9,1,10,7};
int *pntrToMyArray=myArray;
//at this point myArray and pntrToMyArray are exactly the same.
//note also that you can pass myArray directly to a function that uses int* as a parameter type
//if you need to make a copy of the array you will need a loop
Labdabeta 182 Posting Pro in Training Featured Poster

First of all, you could save yourself some time on lines 6-10 by just using using namespace std; Also, I assume you are trying to find the interquartile range? In that case this can be done in very simple linear time. Think about this, there are three quartiles (the points separating the four quarters of the data) one of them is the first, one of them is the third, and the one in the middle is usually called the median. Once you have sorted your array, you do not care at all about the values in it. You can access the quartiles simply by using:

int median=numberstore[numberstore.size()/2];//it really is as simple as that
int firstQuartile=numberstore[numberstore.size()/4];//we want the element that is a quarter of the way in
int thirdQuartile=numberstore[(numberstore.size()/4)*3];//this is the most complicated one, but it can easily be derived from the one above

Hope that helped! (I also hope that I am not entirely wrong :P)

Labdabeta 182 Posting Pro in Training Featured Poster

I do not know much about std::sort, but it is easy enough to sort this array manually. I would suggest using an insertion sort for each student entered, since it works really fast if the array is mostly sorted. Here is a sample implementation:

//This function will sort the vector of students
//It works REALLY fast on data that is mostly sorted
//  as such it should be called on the data every time
//  a new piece of data is entered.
void insertionSort(vector<student> &students, bool (*areInOrder)(student&,student&))
{
    for (int i=0; i<students.size(); ++i)
    {
        student thisStudent=students[i];//this will help make swapping faster
        int x=i-1;//this stores the index we want to swap to
        bool done=false;
        while (!done)
        {
            if (!areInOrder(student[x],students[i]))
            {
                //we will need to swap them
                students[x+1]=students[x];
                --x;
                if (x<0)
                {
                    //we must be done!
                    bone=true;
                }
            }
        }
        students[x+1]=thisStudent;
    }
}

Also the problem may be in your sort_by_name function. The std::string's > operator might not sort in ascending order, but may instead sort by location in memory. Perhaps you will have to wright your own? (compare ASCII values until you find a difference?)

Labdabeta 182 Posting Pro in Training Featured Poster

putAt was just a place holder for what would have to be some kind of platform dependent code. In your case a viable implementation would be:

void putAt(int x, int y, char chr)
{
    COORD loc;
    loc.X=x;
    loc.Y=y;
    SetConsoleCursorPosition(hConsole,loc);
    cout<<chr;
}
Labdabeta 182 Posting Pro in Training Featured Poster

Thank you, that is exactly what I was hoping to hear!

Labdabeta 182 Posting Pro in Training Featured Poster

Wow, I just tested it with this code:

#include <iostream>
using namespace std;

int main()
{
    long long int *test=new long long int[100000000000];
    test[                                  99999999999]=10;
    cout<<test[                            99999999999];
    return 0;
}

And it performed without a problem. Considering that I only have 4 gigs of RAM on my machine, can I assume that my compiler is transparently supporting the whole file-writing thing? (if this works then my mass1venum dll (I wrote it as an excercise) will be able to be a lot simpler)

Labdabeta 182 Posting Pro in Training Featured Poster

A) CODE tags make your code easier to read.
B) What is setYear doing?!

void Movie::setYear(int num)
{
while(Year < 2013)//while year < 2013
++Year;//++year
//now year will be... 2013, regardless of num?
}

Perhaps this would work better?

Movie &Movie::setYear(int year)//I am going to return this, to allow for chaining
{
    this->year=year;
    if (this->year>2013)
    {
        this->year=0;//? I do not really know why the year cannot be greater than 2013
    }
    return *this;
}

In case my above code confused you... In every function of every class there exists an 'extra' parameter. This parameter looks like this: const className *this This parameter is a pointer to the class itself. Its methods can be accessed as usual from a pointer (using -> instead of .) and it can be returned by functions.

Labdabeta 182 Posting Pro in Training Featured Poster

How can I check this, and how can I be sure that it will be platform-independant?

Labdabeta 182 Posting Pro in Training Featured Poster

I have a program that dynamically allocates an array and uses it. The thing is that under certain situations this array will get infinitely long. As such I would like to know if/when the array has gotten too long and then start saving it to a file (where length will not be an issue) Here is an example:

unsigned char *myArray=new unsigned char[len];
//if len>max allowed memory:
FILE *myFile=fopen("myFile.dataFile","wb+");
for (int i=0; i<len; ++i)
{
    fprintf("%c",myOtherData[i],myFile);
}
//else
for (int i=0; i<len; ++i)
{
    myArray[i]=myOtherData[i];
}

I was thinking that maybe new[] returns NULL if there is not enough space or something?

Labdabeta 182 Posting Pro in Training Featured Poster

Thank you, that should work!

Labdabeta 182 Posting Pro in Training Featured Poster

Thank you very much!

Labdabeta 182 Posting Pro in Training Featured Poster

A friend of mine recently asked me to help debug some code. I looked through it and it was riddled all over with goto statements. I know why he uses them (he used to program mainly in assembly and batch) and I tried to explain why he should try to refrain from using goto statements. The problem was that he thinks that I just have a personal vendetta against goto statements, and does not believe that they are harmful. Can anybody give me some concrete, indisputable reasons why the goto statement is evil?

Labdabeta 182 Posting Pro in Training Featured Poster

The problem is not the col variable. It is the scores1 and scores2 variables. Basically you tried to access the member of an array (arrays are just pointers) of a variable that was not even an array. The [] operators are almost exclusively for array and array-like objects.

Labdabeta 182 Posting Pro in Training Featured Poster

I would suggest a switch statement. If the user enters the 'down' key, then move the character down, draw it and draw a space in the old position. I feel very strongly that fixing movement to WASD is a bad idea. It should be WASD by default, but should be able to be changed (this is coming from a Dvorak keyboard user. WASD is spread out all over my layout!). Here is the general idea behind what I am saying:

putAt(player.position.x,player.position.y,' ');
switch (user_input)
{
    case up_key:
    --(player.position.y);
    break;
    case right_key:
    ++(player.position.x);
    break;
    case down_key:
    ++(player.position.y);
    break;
    case left_key:
    --(player.position.x);
    break;
    default:
    //what do you want to do here?
}
putAt(player.position.x,player.position.y,player.characterRepresentation);

Of course that code is very much general, you would have to modify it to fit your needs.

Labdabeta 182 Posting Pro in Training Featured Poster

Thank you very much!

Labdabeta 182 Posting Pro in Training Featured Poster

I am getting ready to write a programming competition on Tuesday (the Canadian Computing Competition) and I remember that last year it said that only standard libraries can be used. I was having trouble deciding which libraries are standard. I ended up using windows.h and when I suddenly realized that it was likely not standard I quickly commented-out a bunch of windows specific code. My question is, is there a list somewhere of all of the libraries considered as 'standard' in c++?

Labdabeta 182 Posting Pro in Training Featured Poster

If you check my tags, I am using microsoft windows and windows API.

Labdabeta 182 Posting Pro in Training Featured Poster

Thank you! That was what I suspected, very helpful!

Labdabeta 182 Posting Pro in Training Featured Poster

To what extent does the system endianness effect a program. I know that doing pointer assignment will be affected, and unions are too, but what about bitshift operators? Do they apply to the value, merely emulating real bitshifts, or do they apply to the bits themselves? Are there any other cases where endianness should be taken into account?

Labdabeta 182 Posting Pro in Training Featured Poster

I have not read all of your code, but from a quick scan I would suggest printing a space where the character used to be.

Labdabeta 182 Posting Pro in Training Featured Poster

Here is a simple function that uses just iostream functionality:

string getCommandLine(string prompt)
{
    cout<<prompt<<" ";
    string ret;
    cin>>ret;
    return ret;
}

Is that what you are looking for?

Labdabeta 182 Posting Pro in Training Featured Poster

I believe the point really lies in the comparison between the different big-O values. For example take the problem of sorting a dictionary. Taking a look at two common algorithms, insertion sort and merge sort we want to decide which one to use. Insertion sort's best case scenario is O(n) as opposed to O(nlogn) of merge sort. For large arrays then Insertion sort will be faster in the best case scenario. But looking at worst case we get insertion sort with O(n*n) and merge sort with O(nlogn) now we see that for large arrays merge will be better in the worst case. The question is which to use? If for example the user is going to enter each element individually, an insertion sort will be better because at any step the array will already be mostly sorted, but if we load the dictionary from a file we get all the data at once and then, since the data could be completely unsorted, we would want a merge sort. Basically big-O notation not only helps to bench-mark an algorithm for bragging rights, but also gives you information on when it is most appropriate.