Looks pretty nice, well done. I think I probably would have done something more complicated as far as calculating the person's age, but what you did looks more than sufficient.
"I think I probably would have done something more complicated as far as calculating the person's age, but what you did looks more than sufficient."

Do you mean I should try and make something harder now?

I have to, I already have some ideas Smile I'll post my new program (if I make it) here later.
No no, I mean the way I would have done it would have been overly complicated, probably something like converting birthday and current day into days since [arbitrary base date, like 1/1/1900], then calculating the difference and dividing by 365.25. The way you did it is simpler and probably better.
My new program:


Code:
#include <iostream>
#include <string>

using namespace std;

int main();
string hexToDb(string hex);

int main() {
   
   cout << hexToDb("EF2197312641273021321031232132132132132130921316312321213210222312312321");
   
   return 0;
}

string hexToDb(string hex) {
   string finalString = ".db ";
   string hexSign = "$";
   int counter = 0;
   int i;
   for (i=0;i<hex.size();i+=2) {
      if (counter==29) {
         finalString += hexSign + hex[i] + hex[i+1] + "\n.db ";
         counter = 0;
      }
      else {
         finalString += hexSign + hex[i] + hex[i+1] +",";
      }
      counter ++;
   }
   
   finalString.erase(finalString.size()-1);
   
   return finalString;
}


I decided to play a bit with strings this time.

It's a C++ version of a program I had made in Python, it can be found here.
ScoutDavid wrote:

Code:

   //Assign day, month and year
   char charDay[2];
   strftime(charDay, 15, "%d", d);
   
   char charMonth[2];
   strftime(charMonth, 15, "%m", d);
   
   char charYear[4];
   strftime(charYear, 15, "%Y", d);

   int day = atoi(charDay);
   int month = atoi(charMonth);
   int year = atoi(charYear);




There's a much simpler way to get the day/month/year from a tm structure since those values are actually stored directly in the tm structure:

Code:
       Broken-down  time  is  stored  in  the structure tm which is defined in
       <time.h> as follows:

           struct tm {
               int tm_sec;         /* seconds */
               int tm_min;         /* minutes */
               int tm_hour;        /* hours */
               int tm_mday;        /* day of the month */
               int tm_mon;         /* month */
               int tm_year;        /* year */
               int tm_wday;        /* day of the week */
               int tm_yday;        /* day in the year */
               int tm_isdst;       /* daylight saving time */
           };

       The members of the tm structure are:

       tm_sec    The number of seconds after the minute, normally in the range
                 0 to 59, but can be up to 60 to allow for leap seconds.

       tm_min    The number of minutes after the hour, in the range 0 to 59.

       tm_hour   The number of hours past midnight, in the range 0 to 23.

       tm_mday   The day of the month, in the range 1 to 31.

       tm_mon    The number of months since January, in the range 0 to 11.

       tm_year   The number of years since 1900.

       tm_wday   The number of days since Sunday, in the range 0 to 6.

       tm_yday   The number of days since January 1, in the range 0 to 365.

       tm_isdst  A  flag  that  indicates  whether  daylight saving time is in
                 effect at the time described.  The value is positive if  day‐
                 light  saving time is in effect, zero if it is not, and nega‐
                 tive if the information is not available.

(That was ripped from the localtime(1) man page on my Linux system Smile)

You would only have to use tm_day, tm_mon+1, and tm_year+1900 to get the actual day, month, and year. Other than that, the rest of your code looks good. Good Idea
It might be simpler, but I don't consider it much simpler. It's pretty much the same thing and the same length of code. Either way, thanks for the feedback Smile What about the other program I made?
ScoutDavid wrote:
It might be simpler, but I don't consider it much simpler. It's pretty much the same thing and the same length of code. Either way, thanks for the feedback Smile What about the other program I made?

It really is simpler and quite a bit shorter. You can replace this code:

Code:
   //Assign day, month and year
   char charDay[2];
   strftime(charDay, 15, "%d", d);
   
   char charMonth[2];
   strftime(charMonth, 15, "%m", d);
   
   char charYear[4];
   strftime(charYear, 15, "%Y", d);

   int day = atoi(charDay);
   int month = atoi(charMonth);
   int year = atoi(charYear);

with this:

Code:
   int day = d->tm_mday;
   int month = d->tm_mon+1;
   int year = d->tm_year+1900;

No strings needed. Smile
I haven't had much time to look at your newer program yet, though.
EDIT: fixed my code. Surprised
Oh I didn't know we could access variables inside structs with the -> operator. Thanks Smile
ScoutDavid wrote:
Oh I didn't know we could access variables inside structs with the -> operator. Thanks Smile

For a struct you use the dot (.) operator. For a pointer to a struct you use the -> operator. The -> operator is equivalent to dereferencing the pointer and using the dot operator. Hopefully this example code will clarify what I mean:

Code:
  struct foo { int x; };
  struct foo a;
  struct foo *b = &a;
  /* 'a' is of type 'struct foo', 'b' is a pointer to type 'struct foo' (it points to 'a' in this case) */
 
  a.x = 1;
  b->x = 2;
  (*b).x = 2; /* same as previous line */
Thanks christop, that was very nice Smile


Code:
#include <iostream>
#include <fstream>
#include <string>

using namespace std;

int main();
string find_and_replace(string source, string const find, string const replace);

int main () {
   string line;
   ifstream myfile ("samplecode.py");
   int loop = 0;
   
   string array[7];
   string array_no_tabs[7];
   
   if (myfile.is_open()) {
      while (! myfile.eof() ) {
         getline (myfile,line);
         array[loop] = line;
         array_no_tabs[loop] = find_and_replace(line, "\t", "");
         cout << array[loop] << endl;
         loop++;
      }
      myfile.close();
   }
   else {
      cout << "Unable to open file";
   }
   
   int i;
   for (i=0;i<7;i++) {
      if (array_no_tabs[i].substr(0,5) == "print") {
         array[i] = "#"+array[i];
      }
      cout << array[i] << endl;
   }
   
   return 0;
}

string find_and_replace(string source, string const find, string const replace) {
   /* This functions find and replaces arg2 with arg3 in a string which is arg1, it returns a new string */
   for(string::size_type i = 0; (i = source.find(find, i)) != string::npos;)
   {
      source.replace(i, find.length(), replace);
      i += replace.length() - find.length() + 1;
   }
   return source;
}


I made this program, it comments all lines that start with "print" (for Python) in a file and prints the new version.

However, it only works for files with 7 lines, I need to give the array an unknown size. I have no idea of how to do it though.

Help please? Thanks
Use malloc, which allows you to allocate memory.
souvik1997 wrote:
Use malloc, which allows you to allocate memory.


Yeah I know I can either use malloc( or a vector. I would prefer to use malloc( but I don't know how to declare an array with allocated memory.
ephan wrote:
souvik1997 wrote:
Use malloc, which allows you to allocate memory.


Yeah I know I can either use malloc( or a vector. I would prefer to use malloc( but I don't know how to declare an array with allocated memory.

Wikipedia has an example in C on how to use the allocated memory as an array.
http://en.wikipedia.org/wiki/Malloc#Dynamic_memory_allocation_in_C
To make an array of a data type, you do (And I am using a Point struct to do it with, just as an example)
Code:
struct Point { int x, int y };
#define ARRAY_SIZE 120

int main(int argc, char** argv) {
  struct Point* pointarray;
  pointarray = malloc(ARRAY_SIZE * sizeof(struct Point));

  pointarray[1].x = 20;
  pointarray[1].y = 30;
 
  printf("X: %d\nY: %d\n",pointarray[1].x, pointarray[1].y);
}
souvik1997 wrote:

Wikipedia has an example in C on how to use the allocated memory as an array.
http://en.wikipedia.org/wiki/Malloc#Dynamic_memory_allocation_in_C


That example implies that the coder knows the size of the array (10) and I had seen it before. I don't know the size of my array.


Code:

struct Point* pointarray;
pointarray = malloc(ARRAY_SIZE * sizeof(struct Point));


Hm, from what I see there, I thought about this:


Code:

string array[]*; //This isn't done like this, but somehow define a pointer to an array


However, can I define a pointer to an array that I haven't declared? I just can't declare it.

Thanks Smile
Wait, what? these two lines are exactly the same:
Code:
int array[];
int* array
So, to make a pointer to a pointer to an array:
Code:
int** array; //or
int* array[];
For instance, to declare an array with a user-specified size, you would do:
Code:
int main(int argc, char** argv) {
  int a = atoi(argv[1]);
  int* array = malloc(a * sizeof(int));
}

Code:
int* my_array = malloc(120 * sizeof(int));


I get this:

g++ wrote:
removeprint.cpp:16:50: error: invalid conversion from ‘void*’ to ‘int*’


I was trying to give it 120mb size.

EDIT
Program Finished, even put it in a packed function:


Code:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>

using namespace std;

int main ();
string find_and_replace(string source, string const find, string const replace);
void comment_lines_starting_with_print_on_file (char input_filename[], char output_filename[]);

int main () {
   char inputFile[] = "samplecode.py";
   char outputFile[] = "output.py";
   comment_lines_starting_with_print_on_file(inputFile, outputFile);
   
   return 0;
}

void comment_lines_starting_with_print_on_file (char input_filename[], char output_filename[]) {
   /* This functions opens a file, comments out (#) all lines starting with "print" and makes a new file with the changes */
   
   string line;
   ifstream myfile (input_filename);
   int loop = 0;
   vector<string> array;
   vector<string> array_no_tabs;
   
   if (myfile.is_open()) {
      while (! myfile.eof() ) {
         getline (myfile,line);
         array.push_back(line);
         array_no_tabs.push_back(find_and_replace(line, "\t", ""));
         loop++;
      }
      myfile.close();
   }
   else {
      cout << "Unable to open file";
   }
   
   int i;
   for (i=0;i<array.size();i++) {
      if (array_no_tabs[i].substr(0,5) == "print") {
         array[i] = "#"+array[i];
      }
   }
   
   ofstream new_file;
   new_file.open (output_filename);
   
   for (i=0;i<array.size();i++) {
      new_file << array[i] << endl;
   }
   new_file.close();
}

string find_and_replace(string source, string const find, string const replace) {
   /* This functions find and replaces arg2 with arg3 in a string which is arg1, it returns a new string */
   
   for(string::size_type i = 0; (i = source.find(find, i)) != string::npos;)
   {
      source.replace(i, find.length(), replace);
      i += replace.length() - find.length() + 1;
   }
   return source;
}


It worked for me, like it?
FWIW, the problem was because malloc() returns a void* (A general pointer). You need to cast it to be an int*. You would do that like:
Code:
int* array = (int*)malloc(120*sizeof(int));
(Sorry, I haven't really done this myself, though I know how to do it... That should work, AFAIK.)
_player1537 wrote:
FWIW, the problem was because malloc() returns a void* (A general pointer). You need to cast it to be an int*. You would do that like:
Code:
int* array = (int*)malloc(120*sizeof(int));
(Sorry, I haven't really done this myself, though I know how to do it... That should work, AFAIK.)


Yap it works, my question being, how to get the size (number of elements) of an array created this way?

I already added stuff to the array that I declared that way. Now how to get size? Thanks.

I tried this, output is "Segmentation Fault":


Code:
#include <iostream>
#include <fstream>
#include <string>
#include <vector>
#include <cstdlib>

using namespace std;

int main ();
string find_and_replace(string source, string const find, string const replace);
void comment_lines_starting_with_print_on_file (char input_filename[], char output_filename[]);

int main () {
   char inputFile[] = "samplecode.py";
   char outputFile[] = "output.py";
   comment_lines_starting_with_print_on_file(inputFile, outputFile);
   
   return 0;
}

void comment_lines_starting_with_print_on_file (char input_filename[], char output_filename[]) {
   /* This functions opens a file, comments out (#) all lines starting with "print" and makes a new file with the changes */
   
   string line;
   ifstream myfile (input_filename);
   int loop = 0;
   
   string* array = (string*)malloc(10*sizeof(string));
   
   //int* array = (int*)malloc(120*sizeof(int));
   
   //vector<string> array;
   vector<string> array_no_tabs;
   
   if (myfile.is_open()) {
      while (! myfile.eof() ) {
         getline (myfile,line);
         //array.push_back(line);
         array[loop] = line;
         array_no_tabs.push_back(find_and_replace(line, "\t", ""));
         loop++;
      }
      myfile.close();
   }
   else {
      cout << "Unable to open file";
   }
   
   int i;
   for (i=0;i<(sizeof array/sizeof(string));i++) {
      if (array_no_tabs[i].substr(0,5) == "print") {
         array[i] = "#"+array[i];
      }
   }
   
   ofstream new_file;
   new_file.open (output_filename);
   
   for (i=0;i<(sizeof array/sizeof(string));i++) {
      new_file << array[i] << endl;
   }
   new_file.close();
}

string find_and_replace(string source, string const find, string const replace) {
   /* This functions find and replaces arg2 with arg3 in a string which is arg1, it returns a new string */
   
   for(string::size_type i = 0; (i = source.find(find, i)) != string::npos;)
   {
      source.replace(i, find.length(), replace);
      i += replace.length() - find.length() + 1;
   }
   return source;
}
The best way, as I'm sure you can guess, is to just use a variable to keep track of the size. Perhaps even better, you could wrap it in a struct. For instance:
Code:
struct STRING_ARRAY {
  int size;
  string* array;
}
And then you could just do:
Code:
int main(int argc, char** argv) {
  STRING_ARRAY stringArray = { 20, (string*)malloc(20*sizeof(string)) };
 
  int i;
  for(i=0;i<stringArray.size;i++)
    printf("%s\n",stringArray.array[i]);

  free(stringArray.array);
}


Edit: You could even set up a function to create a STRING_ARRAY, given a size, and a place to store everything.

Code:
void createStringArray(STRING_ARRAY* stringArray, int size) {
  stringArray->size = size;
  stringArray->array = (string*)malloc(size*sizeof(string));
}
destroyStringArray(STRING_ARRAY* stringArray) {
  free(stringArray->array);
}
And then you would use them like:
Code:
int main(int argc, char** argv) {
  STRING_ARRAY stringArray = new STRING_ARRAY;
  createStringArray(&stringArray, 20);
 
  //...
 
  destroyStringArray(&stringArray);
}
  
Register to Join the Conversation
Have your own thoughts to add to this or any other topic? Want to ask a question, offer a suggestion, share your own programs and projects, upload a file to the file archives, get help with calculator and computer programming, or simply chat with like-minded coders and tech and calculator enthusiasts via the site-wide AJAX SAX widget? Registration for a free Cemetech account only takes a minute.

» Go to Registration page
» Goto page Previous  1, 2, 3, 4, 5, 6, 7, 8, 9, 10  Next
» View previous topic :: View next topic  
Page 8 of 10
» All times are UTC - 5 Hours
 
You cannot post new topics in this forum
You cannot reply to topics in this forum
You cannot edit your posts in this forum
You cannot delete your posts in this forum
You cannot vote in polls in this forum

 

Advertisement