Programming (C++, Java, VB, etc)

No language too crude. No topic too obscure.
The one and only section of these forums where anything goes...

Programming (C++, Java, VB, etc)

Postby Simion32 » December 11th, 2009, 2:47 am

Here's a topic where you can discuss programming - coding styles, semantics, etc.

In general I'm most experienced with C++, next to a little Visual Basic.

const char* array = "DKC Atlas - Where 101% just isn't enough.\0";
for(int i = 0,array[i],i++){cout << array[i];}
Sage of Discovery
Bananas received 333
Posts: 2741
Joined: 2008

Re: Programming (C++, Java, VB, etc)

Postby Cyclone » December 11th, 2009, 2:54 am

Yea I was thinking on creating a topic like this to post random bits of code to help myself remember.

As for posting strings.... I was being a little silly in the code I posted in the random thought topic. ;) . I know the correct way is:

Char string[] = {"This is a string"};

There's also no string type in c++.

In your example that's a string constant and the compiler creates a string table for things like that. char* just points to that string table. And the cout statment ignores spaces which is why you need a for loop. But i'm a total beginer and still reading that book. Classes look really interesting but it hasn't covered that yet.

C++ Beginier's Guide.
Expedition Leader
Bananas received 559
Posts: 1211
Joined: 2008

Re: Programming (C++, Java, VB, etc)

Postby Cyclone » December 11th, 2009, 5:44 am

Why did you remove your post?

by the way I thnk you need to recheck your code in the random thoughts topic. ;)
Expedition Leader
Bananas received 559
Posts: 1211
Joined: 2008

Re: Programming (C++, Java, VB, etc)

Postby Simion32 » December 11th, 2009, 6:16 am

Well, I don't want to flood this topic with details on DELTA... :roll:

I'll probably repost it or something in the DKCLB topic. I realized that the post would have fit there more than in this topic.
Sage of Discovery
Bananas received 333
Posts: 2741
Joined: 2008

Re: Programming (C++, Java, VB, etc)

Postby Cyclone » December 20th, 2009, 6:47 pm

This is my first true c++ program. I had to give myself a pat on the back. I did this all from memory and did not use the online book for help. :D

This program sorts an array of letters in correct alphabetical order.

Code: Select all
#include "stdafx.h"
#include <iostream>
#include <cstring>
using namespace std;

int main()
{
   char str[] = "ishpcm";
   int left = 0; int right; char x;

   for(left = 0; left <= strlen(str)-1; left++)
   {
      for(right = strlen(str)-1; right > left; right--)
      {
         if(str[right] <= str[left])
         {
            char x = str[left];
            str[left] = str[right];
            str[right] = x;
         }
      }
   }
   cout << str << "\n";
}



I'm not sure if there are any mistakes in the code but the program seems to work.

This topic feels kinda lonely. I doubt there are many programmers here. :|
Expedition Leader
Bananas received 559
Posts: 1211
Joined: 2008

Re: Programming (C++, Java, VB, etc)

Postby Simion32 » December 31st, 2009, 5:59 pm

Here's a useful little routine that I found somewhere on the internet. Might be useful for DKCLB later on.

// Fast Integer Square-Root Routine:
unsigned short isqrt(unsigned long a)
{
unsigned long rem = 0;
unsigned long root = 0;
for(int i = 0;i < 16;i++)
{
root <<= 1;
rem = ((rem << 2) + (a >> 30));
a <<= 2; root++;
if(root <= rem)
{
rem -= root;
root++;
}
else{root--;}
}
return (unsigned short)(root >> 1);
}

I can't remember who made this or where I got the function from, but I do remember it took an awful lot of digging around to find.
Sage of Discovery
Bananas received 333
Posts: 2741
Joined: 2008

Re: Programming (C++, Java, VB, etc)

Postby Cyclone » January 1st, 2010, 5:12 pm

^ If I remember correctly operating on the individual bits of a variable is supposed to be faster then other methods. I'm assuming that's why you went looking for it as there is built in sqrt() library function.
Expedition Leader
Bananas received 559
Posts: 1211
Joined: 2008

Re: Programming (C++, Java, VB, etc)

Postby Simion32 » January 2nd, 2010, 8:12 am

Yeah, and I also wanted a square root function that worked with integers, because DELTA's physics system uses "fixed-point" integer math. Converting to double and back would make the operation slow. So I figured I may as well find a fast way of doing integer square roots.
Sage of Discovery
Bananas received 333
Posts: 2741
Joined: 2008

Re: Programming (C++, Java, VB, etc)

Postby Cyclone » January 13th, 2010, 6:08 pm

Heres a question for you Simion if you can pull yourself away from DELTA :D

I wrote this program that searches for words in a text file and it works fine except for one thing... I am using the new function to dynamically create an array of characters which is used for the search. It works fine but when ever I try to delete it using the delete function the program hangs. I have tried to put the delete function in different areas of the program but still with no success.

Got any ideas? Below is the code and cpp file. And yes there is a lot of redundency in the comments. :roll:

Edit: Attachments are broken?

Spoiler!
Code: Select all


#include "stdafx.h"
#include <iostream>
#include <fstream>
using namespace std;

// Function templates(prototypes)
void Show_Menu(); // Show the menu
void Search_Parameters(); // Define the search parameters. Ask the user what they want to search for.
int find(char search[], ifstream &in); // Search function.


void main()
{   
   /*** Display Menu ***/
   Show_Menu();

   /*** Exit Program ***/
   return;
}

void Show_Menu()
{
   /*** Display Menu ***/
   cout << "Basic File Editor\\Searcher\n\n";
   
   cout << "Search:\n";
   cout << "1. Search A File For Text\n";
   cout << "2. Search A File For Dec\n";
   cout << "3. Search A File For Hex\n";
   cout << "4. Search A File For Binary\n";

   cout << "\nEdit:\n";
   cout << "5. Edit A File Using Text\n";
   cout << "6. Edit A file Using Dec\n";
   cout << "7. Search A File For Hex\n";
   cout << "8. Search A File For Binary\n";
   cout << "9. Exit\n";

   int s = 0;
   while(s!=9)
   {
      cout << "\nPlease Select An Option: ";
      cin >> s;
      switch (s)
      {
         case 1:
         cout << "\n";
         Search_Parameters();
         s=9;
         break;

         case 2:
         cout << "Not Finished\n";
         break;

         case 3:
         cout << "Not Finished\n";
         break;

         case 4:
         cout << "Not Finished\n";
         break;

         case 5:
         cout << "Not Finished\n";
         break;

         case 6:
         cout << "Not Finished\n";
         break;

         case 7:
         cout << "Not Finished\n";
         break;

         case 8:
         cout << "Not Finished\n";
         break;

         case 9:
         break;

         default:
         break;
      }
   }

   return;
}

void Search_Parameters() // Define the search parameters. Ask the user what they want to search for.
{
   /*** Declare Variables ***/
   //char search[100]; // Store the search term in a character array.
   char *search= new char[]; // or use a pointer to a new array of unknown size.
   char yn[100]; // Store the yes\no answer in a character array.
   yn[0] = 'y'; // Initialize to yes, so the program actually runs. :)


   /*** Open file ***/
   ifstream in("c:/test.txt", ios::in | ios::binary); // Open a binary input stream.


   /*** Run the Search ***/
   while(yn[0]!= 'n') // Loop the search program until user enters 'n' to end the program.
   {
      cout << "Type a word or sentence to search for: ";
      cin >> gets(search); // Using the built in get function allows you to get multiple words. The standard cin >> function stops when it encounters a whitespace.
      cout << find(search, in) << " matches found.\n"; // Run the 'search' function and display the results.

      cout << "Search again? (y\\n): "; // The backslash before the '\n' is needed so that the console treats '\n' as two seperate characters instead of the newline escape character.
      cin >> gets(yn);
      if(yn[0]=='n'){break;} // Break out of the search loop.
      cout << "\n";
   }
   
   cout << "\n\n";
   in.close();Show_Menu(); // Close the file and show the menu.
   return;
}

int find(char search[], ifstream &in) // Search function. The ifstream is passed to this function by reference.
{
   /*** Create temp array and initialize the variables. ***/
   int n;
   for(n=0;search[n-1];n++){} // Count how many characters are in the search term.
   char *found = new char[n]; // Temp array. Creates a new array with the same number of elements as the search term.
   char ch; // Buffer for storing each character(byte) found by in.get().
   int offset = 0; // The offset is used to tell the seekg() function where to start looking in the file.
   int counter = 0; // Start counter at 0 for each new search.


   /*** Start searching untill the end of the file(eof) has been reached. ***/
   for(int h=0; !in.eof();h++)
   {
      in.seekg(offset); // Start at the beggining of the file if offset is 0 or got to next byte if offset has been incremented by the loop.
      in.get(ch); // Get a single character(byte) from the file.
      found[0] = ch; // Store the found byte into the array.

      if(found[0] == search[0]) // If a match is found for the first character in the search
      {                    // then start checking for matches for the next characters.
         if(n != 2) // If the search term is more then one character continue on checking for matches for the next letters.
         {
            for(int i=1; i<=(n-1); i++)
            {
               offset++;
               in.seekg(offset);
               in.get(ch);
               found[i] = ch;
               if(found[i] != search[i]) {break;} // If the found letter doesn't match the one in the seach term then end the loop.
               if(found[n-2] == search[n-2]) // If the last character in both the found array and search array then a match has been found.
               {
                  counter++; // Found a match so add 1 to the counter.
                  for(int c=0;c<=n;c++) // Clear the array after each match.
                  {
                     found[c] = 0;

                  }   
               }
            }
      
         } else {counter++;offset++;} // If the first character matches a sinlge character search term then a match has been found so add 1 to the counter.
      }
      else {offset++;} // If the above loops finished then increment the offset by one byte and continue searching the file for the seach term.
   }
   
   in.seekg(0); // Once the file has been search reset the seekg() function to the beginning of the file so that the user can search again with a differen word.
   return counter; // Return the number of matches found.
}

Expedition Leader
Bananas received 559
Posts: 1211
Joined: 2008

Re: Programming (C++, Java, VB, etc)

Postby Simion32 » January 14th, 2010, 6:10 am

Code: Select all
   char *search= new char[]; // or use a pointer to a new array of unknown size.
   char yn[100]; // Store the yes\no answer in a character array.

You've got to define the size when using new, you can't new an unknown size. Generally it should be:

char *search= new char[0x100];//Allocate 256 characters
delete[] search;//Later, delete the allocated memory
search = NULL;//Also set the pointer to NULL just in case


Also, I'd like to mention that doing:
char Array[8][2] = {0};//Creates a block of 16 chars using one pointer
---is not the same thing as---
char **Array = new char*[8];//Allocate 8 char pointers to Array
for(int x = 8,x != 0;x--)//Now use those pointers...
{Array[x] = new char[2];}//...allocating 2 chars to each pointer

The first one is always a char*, no matter how many array dimensions you use. The second is pointer to array of char*.
Sage of Discovery
Bananas received 333
Posts: 2741
Joined: 2008

Re: Programming (C++, Java, VB, etc)

Postby Cyclone » January 14th, 2010, 7:48 pm

Thanks, I kinda figured the unsized array was the problem. I did try the sized array which if you noticed was commented out. What prevented the sized array from working was the function gets() . To fix I used getline() instead.

Is there any reason in particular you specified the size of the array using a hex value?
Expedition Leader
Bananas received 559
Posts: 1211
Joined: 2008

Re: Programming (C++, Java, VB, etc)

Postby Doogie » February 28th, 2010, 7:51 pm

Cyclone wrote:Thanks, I kinda figured the unsized array was the problem. I did try the sized array which if you noticed was commented out. What prevented the sized array from working was the function gets() . To fix I used getline() instead.

Is there any reason in particular you specified the size of the array using a hex value?


He is probably just used to coding that way for DELTA as fixed-point notation is easier to understand in hex then values.
Newcomer
Posts: 2
Joined: 2010

Re: Programming (C++, Java, VB, etc)

Postby Simion32 » July 15th, 2010, 6:29 am

This was the slice of code that I never did post in the DELTA topic, because it's now unused due to my finding out about MMX and using inline assembly instead (which by the way is several orders of magnitude faster than raw C++).

I finally found this thing again in a random text file and thought I'd post it for all to see. ;)

unsigned long int srcpx = 0x12AC5B;
unsigned long int dstpx = 0xFC1145;

int sum = ((dstpx & 0x7F7F7F)+(srcpx & 0x7F7F7F));
int ovf = ((dstpx & 0x808080)+(srcpx & 0x808080)+(sum & 0x808080));
int msk = ((ovf>>1) & 0x808080);
msk |= (msk>>1);
msk |= (msk>>2);
msk |= (msk>>4);
dstpx = ((ovf & 0x808080) | (sum & 0x7F7F7F) | msk);

//Result of calculation should be: 0xFFBDA0

What this does is add together two RGB pixels, saturating the values at 255 if the addition overflows. All done without conditional jumps. The only catch is that the alpha value will probably get clobbered in the process (which was by design).

The same thing in MMX assembly is roughly:
#This code accounts for Magic Pink (which results in adding nothing).
#This processes two pixels at a time, as well.
# Register esi is the source pixel pointer.
# Register edi is the destination pixel pointer.
# mm7 == 00FF00FF 00FF00FF

movq (%%esi), %%mm1
movq %%mm7, %%mm3
pcmpeqd %%mm1, %%mm3
pandn %%mm1, %%mm3
movq (%%edi), %%mm2
paddusb %%mm3, %%mm2
movq %%mm2,(%%edi)
Sage of Discovery
Bananas received 333
Posts: 2741
Joined: 2008


Return to Anything Goes

Who is online

Users browsing this forum: No registered users and 11 guests

cron