?
Solved

c++ class, creating an object using a constructor

Posted on 2003-03-13
4
Medium Priority
?
433 Views
Last Modified: 2008-02-01
hi, i have a program which reads in files and does various things with them. it doesn't quite work yet because whenever i try to run the file i get "Segmentation Fault (core dumped)" error so i cant test anything else.  I cant see what's wrong with the program so if somebody could help me that would be superb.  cheers,

tim


C++ Code, the error is in the first line of 'main' - creating the object:
#include <math.h>
#include <stdio.h>
#include <stdlib.h>
#include <fstream.h>
#include <iostream.h>

/*----------------------------------------------------------------------------------------------------------------*/

struct Player {
      char* id;
      char* name;
      double ranking;
};

/*----------------------------------------------------------------------------------------------------------------*/

using namespace std;

/*----------------------------------------------------------------------------------------------------------------*/

class matches {
      public:
            matches();
            ~matches();
      //      int max_name_length;
      //      int noOfPlayers;
            bool isStatement(char test[]);
            bool isID(char test[]);
            char * LTrim (char trim[]);
            char * RTrim (char trim[]);
            char * Trim (char trim[]);
            char * RemoveSpaces (char trim[]);
            Player selectDetails(Player player, char test[], int testLength);
            void doWork();


      //      char * participants;





};

matches::matches() {
}

matches::~matches() {
}

/*----------------------------------------------------------------------------------------------------------------*/

bool matches::isStatement(char test[]) {
      for (int x=0; x<strlen(test); x++) {
            if (test[x] != ' ') {
                  if (test[x] == '/' && test[x+1] == '/') {
                        return true;
                  } else {
                        return false;
                  } // end if-else
            } // end if
      } // end for
} // end function: isStatement

/*----------------------------------------------------------------------------------------------------------------*/

bool matches::isID(char test[]) {
      // Get ascii value from char to check for alpha-numeric value
      int ascOne = int(test[0]);
      // Check the first character is a capital letter
      if (ascOne < 91 && ascOne > 64) {
            // Check the last character is a number
            if (test[1] < 58 && test[1] > 47) {
                  return true;
            } else {
                  return false;
            } // end if-else
      } else {
            return false;
      }// end if-else
} // end function: checkForID

/*----------------------------------------------------------------------------------------------------------------*/

char* matches::LTrim (char trim[]) {
      do {
            if (trim[0] != ' ') {
                  return trim;
            } else {
                  for (int x = 0; x < strlen(trim)-1; x++) {
                        trim[x] = trim[x+1];
                  }
                  trim[strlen(trim)-1] = '\0';
            }
      } while (trim[0] == ' ');
      return trim;
}

/*----------------------------------------------------------------------------------------------------------------*/

char* matches::RTrim (char trim[]) {
      do {
            if (trim[strlen(trim)-1] != ' ') {
                  return trim;
            } else {
                  trim[strlen(trim)-1] = '\0';
            }
      } while (trim[strlen(trim)-1] == ' ');
      return trim;
}

/*----------------------------------------------------------------------------------------------------------------*/

char* matches::Trim (char trim[]) {
      return LTrim(RTrim(trim));
}

/*----------------------------------------------------------------------------------------------------------------*/

char* matches::RemoveSpaces (char trim[]) {
      for (int x = 0; x < strlen(trim); x++) {
            if (trim[x] == ' ') {
                  do {
                        for (int y = x; y < strlen(trim)-1; y++) {
                              trim[y] = trim[y+1];
                        } // end for
                        trim[strlen(trim)-1] = '\0';
                  } while (trim[x] == ' ');
            } // end if
      } // end for
return LTrim(RTrim(trim));
}

/*----------------------------------------------------------------------------------------------------------------*/

Player matches::selectDetails(Player player, char test[], int testLength) {
      // Declare local variables
      int strPos=0, strLen=0, tracker=0;
      char *temp;
      player.ranking = 0;

      ////////////////////
      ///Read in the id///
      ////////////////////

      // Skip initial spacing
      do { strPos++; } while (test[strPos] == ' ');

      // Work out length of text
      strLen = strPos;
      do { strLen++; } while (test[strLen] != ' ');
      strLen -= strPos;

      // Declare struct array length using DMA
      player.id = new char[strLen];

      // Read all the characters until a space is reached
      tracker = 0;
      do {
            player.id[tracker] = test[strPos];
            strPos++;
            tracker++;
      } while (tracker != strLen);
      player.id[strLen] = '\0';      


      //////////////////////
      ///Read in the name///
      //////////////////////

      // Skip next spacing
      do { strPos++; } while (test[strPos] == ' ');

      // Work out length of text
      strLen = strPos;
      do { strLen++; } while (test[strLen] != ' ');
      strLen -= strPos;

      // Declare struct array length using DMA
      player.name = new char[strLen];

      // Read all the characters until a space is reached
      tracker = 0;

      do {
            player.name[tracker] = test[strPos];
            strPos++;
            tracker++;
      } while (tracker != strLen);
      player.name[strLen] = '\0';


      /////////////////////////
      ///Read in the ranking///
      /////////////////////////

      // Skip next spacing
      do { strPos++; } while (test[strPos] == ' ');

      // Work out length of text
      strLen = strPos;
      do { strLen++; } while (strLen != strlen(test));
      strLen -= strPos;

      // Declare struct array length using DMA
      temp = new char[strLen];

      // Read all the characters until a space is reached
      tracker = 0;
      do {
            temp[tracker] = test[strPos];
            strPos++;
            tracker++;
      } while (tracker != strLen);
      temp[strLen] = '\0';
      
      // The array 'temp' now contains the characters of the ranking.  We need to convert them to an integer
      for (int n = 0; n < strlen(temp); n++) {
            player.ranking += (temp[n]-48) * pow(10,strlen(temp)-n-1);
      } // end for
return player;
}

/*----------------------------------------------------------------------------------------------------------------*/

void matches::doWork () {
      // Declare variables
      int counter = 0;
      char buffer[256];
      char participants[256];
      Player *players;

      // Open file streams
      ifstream playerfile ("players.dat");
      ifstream participantsfile ("participants.dat");


      // Error handling for file-opening
      if (!playerfile.is_open()) { cout << "Error opening player file"; exit(1); } // end if
      if (!participantsfile.is_open()) { cout << "Error opening participants file"; exit(1); } // end if

      // Read in the participants
      do {
            participantsfile.getline (buffer, 100, '\n');
            if (!isStatement(buffer)) {
                  int noOfPlayers = strlen(RemoveSpaces(buffer));
                  participants = buffer;
                  players = new Player[noOfPlayers];
                  for (int n = 0; n < noOfPlayers*2; n+2) {
                        players[n/2].id[0] = participants[0];
                        players[n/2].id[1] = participants[1];
                  }
            } // end if
            cout << participants;
      } while (! participantsfile.eof());
      
      cout << participants << endl;
      
      for (int n = 0; n < strlen(participants); n++) {
            cout << "HELLO";
            cout << participants[n] << buffer[n] << endl;
      } // end for

      //Start searching the file for player details
      do {
            //Read in one line at a time
                  playerfile.getline (buffer, 100);

            // If the line is not a statement (//) then call function to get player details
            if (!isStatement(buffer)) {
//                  player[counter] = selectDetails(player[counter], buffer, strlen(buffer));
//                  cout << "Name: " << player[counter].name << endl;
//                  cout << "ID: " << player[counter].id << endl;
//                  cout << "Ranking: " << player[counter].ranking << endl;
//                  cout << endl;
            }
      } while (! playerfile.eof());       // end while
      
      // Close the file streams
      participantsfile.close();
      playerfile.close();
      
      // Print out the array of players and their details
      for (int n = 0; n <25; n++ ) {
//                  cout << player[n].id;
      }

}

/*----------------------------------------------------------------------------------------------------------------*/

int main() {
      matches details;
      details.doWork();
return 0;
} // end function: main
0
Comment
Question by:FatBoyTim
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
4 Comments
 

Expert Comment

by:Polymorphic
ID: 8133813
what compiler are you using
0
 
LVL 1

Accepted Solution

by:
ilikenine earned 500 total points
ID: 8134082
I guess problem is here

players = new Player[noOfPlayers];
               for (int n = 0; n < noOfPlayers*2; n+2) {
                    players[n/2].id[0] = participants[0];
                    players[n/2].id[1] = participants[1];
               }


You are saying New of Player struct.
But the id in this itself is char*, you haven't assigned any memory for this and trying to allocate a value to it. Thus it will give a segmentation fault.

Just to test if i am right or wrong, change the struct Player to
struct Player {
     char id[100];
     char name[200];
     double ranking;
};

Then compile and run, see what happens.

cheers
GG
0
 
LVL 30

Expert Comment

by:Mayank S
ID: 8134339
Ilikenine's comment is good, but if you want to continue using your pointer-declaration, then after writing:

players = new Player[noOfPlayers];

write:

for ( i = 0 ; i < noOfPlayers ; i ++ )
{
  players[i].id = new char[<whatever-size>] ;
  players[i].name = new char[<whatever-size>] ;

} // end for


AND OH!

CHECK THE UPDATION OF YOUR FOR LOOP : you've written simply 'n + 2' --> should it not be 'n = n + 2' or 'n += 2' ????

Mayank.
0
 

Author Comment

by:FatBoyTim
ID: 8135790
cheers for that.  i know the problem was with the constructor and i spent a lot of time trying to find it.  i guess i found it and fixed it, but then posted the message with a different error :-P  thanks for your help everyone, im starting to understand memory allocation quite well now!

fbt
0

Featured Post

Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

This article will inform Clients about common and important expectations from the freelancers (Experts) who are looking at your Gig.
What do responsible coders do? They don't take detrimental shortcuts. They do take reasonable security precautions, create important automation, implement sufficient logging, fix things they break, and care about users.
An introduction to basic programming syntax in Java by creating a simple program. Viewers can follow the tutorial as they create their first class in Java. Definitions and explanations about each element are given to help prepare viewers for future …
In this fifth video of the Xpdf series, we discuss and demonstrate the PDFdetach utility, which is able to list and, more importantly, extract attachments that are embedded in PDF files. It does this via a command line interface, making it suitable …
Suggested Courses

770 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question