Thanks histrungalot, this is a really, really cool suggestion. I'll give it a whirl...

Many thanks! This is an awesome forum! -P

Hola code gurus,

I’m wondering if there’s a way to use a string to access a specific item in a matrix of int[X].

I have a program which uses enums as iterators to reference a large amount of data. To select an item in the matrix, the user will enter a string, which is also an enum, which also must serve as an iterator for something in the matrix. Here is a toybox example:

#include <iostream>
#include <string>
using namespace std;

enum NyNumbers { First, Second, Third, Forth, LAST_VALUE };

int main(int argc, char* argv[]) {

  int Matrix[LAST_VALUE] = { 1, 3, 7, 12 };

  cout<<"Matrix[ atoi("<<argv[1]<<") ]:  ";
  cout<<Matrix[ atoi(argv[1]) ]<<"\n";

  return 0;
}

The idea is the user executes the program by typing “./RUN First” to print out the first element in the MyNumbers array, “./RUN Second” to access the second, and so on. I can’t use static numbers for the iterator. (i.e., “./RUN 1”) I must reference by enum/string.

When run, the output of this problem is thus:

user@debian$ ./RUN Second
Matrix[ atoi(Second) ]:  1
user@debian$

BTW, if I change line 12 to this…

cout<<Matrix[ argv[1) ]<<"\n";

…the error message is this…

user@debian$ make
g++ -g -Wall -ansi -pg -D_DEBUG_   Main.cpp -o exe
Main.cpp: In function `int main(int, char**)':
Main.cpp:12: error: invalid types `int[4][char*]' for array subscript
make: *** [exe] Error 1
user@debian$

…which isn’t unexpected. Any idea how to imput the enum as argv[1]?

Many thanks! -P

Good ideas, thanks for taking a look!

Hi everyone,

I’m Pete, moderately-experienced C++ user who is always looking for better ways to do things.

Let me ask you guys about a problem I’ve scratching my head over lately. Suppose I’m writing a program designed to simulate a large company. I’m interested in tracking each company employee by the location where they work. This company has perhaps a thousand different locations:

[CODE]class Employee {
public:
AccessorFunction1(); // does something
AccessorFunction2(); // does something different
AccessorFunction3(); // does something completely different
protected:
// Some data
};

class Company {
public:
void OrganizeLocation(int a);

protected:
vector<Employee> LocationA;
vector<Employee
> LocationB;
vector<Employee> LocationC;
...etc...
vector<Employee
> LocationZZZ;
};[/CODE]

Once employees are created and pointers to them are saved in the proper Location vector, I write an accessor function, OrganizeLocation(), designed to do a number of operations on a given vector. The problem is, I have maybe a thousand vectors. How do I call this function and specify which vector I want?

Currently, I’m using this clunky solution:

[CODE]void Company::OrganizeLocation(int a){
switch(a) {
case 1: {
for(unsigned int i=0; i<LocationA.size(); i++) {
LocationA[i]->AccessorFunction1();
LocationA[i]->AccessorFunction2();
LocationA[i]->AccessorFunction3();
}
break;
}
case 2: {
for(unsigned int i=0; i<LocationB.size(); i++) {
LocationB[i]->AccessorFunction1();
LocationB[i]->AccessorFunction2();
LocationB[i]->AccessorFunction3();
}
break;
}
case 3: {
// etc...
}
case 4: {
// etc...
}

...etc...

case 1000: {
    // etc...
  }

}
}[/CODE]

The key point here is that whichever vector I choose to operate upon, I’ll do the exact same procedure every time. I hate this solution because it results in very ...

Awesome, these are great tips. Thanks to your feedback, I was able to zero in on the real problem, the order of the included files was complicating matters. I've since rebalanced, and things now look great.

Many thanks!
-P

Sorry, I should have removed the bulk of the main() function. For the purposes of this thread, it should be:

[CODE]int main() {
return 0;
}
[/CODE]

Hi everyone,

Thanks for taking a gander. Below is the full code, a few unrelated things omitted. I've also included the makefile I'm using for good measure. (I'm working on a VMware machine, emulating Solaris.)

      Yours,
            -P

[CODE]#------------------------------------------------------------------------------

File: Makefile

#

Note: This Makefile requires GNU make.

#

(c) 2001,2000 Stanford University

#

------------------------------------------------------------------------------

CC = g++

CFLAGS = -g -Wall -ansi -pg -DDEBUG $(ARCH)

CFLAGS = -g -Wall -Werror -ansi -pg -DDEBUG $(ARCH)

LIBS =

SRCS =

all: exe

exe: $(SRC)
$(CC) $(CFLAGS) $(LIBS) Main.cpp -o exe

.PHONY : clean clean-deps

clean:
rm -f .o ~ core sr .dump .tar tags

clean-deps:
rm -f .*.d

//<><><><><><><><><><><><><><><><><><><><><><><><><><>
//<><><><><><><><><><><><><><><><><><><><><><><><><><>

//"Player.h"

class GameUnit;

class Player {

public:

//Constructors

  Player(int MyID, string MyFactionName);

  ~Player();

//Accessors

  friend class GameUnit;
  int  GetID()  { return ID; }

  string GetFactionName()  { return FactionName; }

  void AddUnit(GameUnit* NewUnit) {MyUnits.push_back(NewUnit);}
  void ListUnits();
  void ListUnitsByPtr();
  Player* FindPlayer(string MyFactionName);

// Other

protected:
int ID;
string FactionName;
vector<GameUnit*> MyUnits;

};

Player::Player(int MyID, string MyFactionName) {
ID=MyID;
FactionName=MyFactionName;
}

Player::~Player() {
// do nothing
}

void Player::ListUnits() {
if(MyUnits.size()>0) {
for(unsigned int i=0; i<MyUnits.size(); i++) {
cout<<MyUnits[i]->GetName()<<", ";
}
cout<<"\n";
}
else cout<<"No Units!\n";
}

void Player::ListUnitsByPtr() {
if(MyUnits.size()>0) {
for(unsigned int i=0; i<MyUnits.size(); i++)
cout<<MyUnits[i]<<", ";
cout<<"\n";
}
else cout<<"No Units!\n";
}

//<><><><><><><><><><><><><><><><><><><><><><><><><><>
//<><><><><><><><><><><><><><><><><><><><><><><><><><>

//"GameUnit.h"

// Enums

enum GameUnit_int
{ Attack, Defend, Cost, Move, Damage, LAST_VALUE_INT };
enum GameUnit_bool
{ JetPower, SuperSubs, LRAircraft, HeavyBombers, LAST_VALUE_BOOL };

class GameUnit {

public:

//Constructors

  GameUnit(string MyName, int a, int b, int c, ...

Hi everyone,

I'm a moderate-level C++ programmer who is a little rusty at the moment. I've got an object question which is driving me nuts. I'm sure this is a C++ 101 level question, but for the life of me, I can't recall the solution. Basically, I've got one object which has to access private data in another object... and can't.

Here's the specifics: I'm writing a little war game program where players deploy units (soldiers, tanks, planes, etc.) onto a gameboard. Players and Units are modeled as objects:

[CODE]class GameUnit {
public:
string GetName() {return Name;}
protected:
string Name;
};

class Player {
public:
void ListUnits();
protected:
vector<GameUnit*> MyUnits;
};

void Player::ListUnits() {
for(unsigned int i=0; i<MyUnits.size(); i++) {
cout<<MyUnits[i]->GetName()<<"\n";
}
}[/CODE]

Here's the problem: In the above code, Player's ListUnits() function doesn't work because Player can't access GameUnit's GetName() function. Specifically, here's the compiler's error message:

[CODE]In file included from Main.cpp:18:
Player.h: In member function 'void Player::ListUnits()':
Player.h:47: error: 'GetName' undeclared (first use this function)
Player.h:47: error: (Each undeclared identifier is reported only once for each function it appears in.)[/CODE]

I've tested enough to realize that the problem is the GameUnit::GetName() function is a public function within the GameUnit object. Why can't a Player call this function? Making both friend classes of each other doesn't help. Do I have to make these guys related somehow?

I'm sure this is a fairly simple problem, but I can't find the solution for the life of me.

          Many thanks,
              -P

Hi everyone,

I'm a moderately experienced C coder trying to figure out the [B]execve()[/B] command. Here's the basic problem:

My program takes a command from the user, loaded into the string UsrCmd. The string is tokenized and each token is loaded into ParaArray[]. Then ParaArray[] is used as arguments to call execve(). I think I also pass in the user's environment variables with envp[].

But here's the problem: If the user inputs a command without the full path to that command, execve() cannot find the associated system call and fails. It is obviously too cumbersome to ask the user to enter the full path for each inputted command. So how do I get execve() to accept the PATH variables?

Below I've included both my code and then two outputs:
-- In the first output, I simply type "ls -l"
-- In the second output, I type "/bin/ls -l"

        Many thanks!
               -P

[code=c]

include <stdio.h>
include <unistd.h>
include <sstream>

using namespace std;

define BUFF_SIZE 1000

int main(int argc, char *argv, char envp[])
{
// Define buffer for user's command
char UsrCmd = (char )malloc(sizeof(char) BUFF_SIZE);
char
token;
char * ParaArray[100];
int ParaIndex = 0; int i = 0;

printf("Here are your Environment Variables:\n");
while(envp[i]!=NULL)
{ printf("%s\n", envp[i]); i++; }

// Get user's command
printf("ENTER A COMMAND: ");
fgets(UsrCmd, BUFF_SIZE+1, stdin);

// We tokenize the user's command and load the tokens into ParaArray
token = strtok(UsrCmd, " \t\n");
ParaArray[ParaIndex] = token; ParaIndex++;
while(token != NULL)
{
token = strtok(NULL, " ...

Hi everyone,

I'm a moderately experienced C++ programmer who's trying to do a little socket work. Don't ask why, but I'm to write a program which, when activated, sends an HTTP POST request to a remote end server. The socket part of the work is done and successfully tested; all I have to do is get the HTTP header exactly right. Unfortunately, the resources I've consulted online aren't that helpful and I can't tell where I'm screwing up the header. Can someone quickly spot the error or recommend a solid resource which will really detail what I want to do?

Here's the HTTP request I'm sending to the remote server:

[CODE]POST /login.jsp HTTP/1.1
Host: 135.51.161.73
Content-Length: 170
Content-Type: text/html; charset=ISO-8859-4

<Payload>...stuff here...</Payload>[/CODE]

For those of you who are curious, here's the code (briefer than it looks):

[CODE]void BuildPayload(string* PtrPayloadBuffer, string Stuff)
{
string Part1="<Payload>";
string Part2="</Payload>";

(PtrPayloadBuffer).clear();
(
PtrPayloadBuffer).append(Part1);
(PtrPayloadBuffer).append(Stuff);
(
PtrPayloadBuffer).append(Part2);
}

void BuildHeader(string PtrHeaderBuffer, string PtrPayloadBuffer, sockaddr_in RemoteServer)
{
string Part1="POST /login.jsp HTTP/1.1\nHost: ";
string Part2="\nContent-Length: ";
string Part3="\nContent-Type: text/html; charset=ISO-8859-4\r\n\r\n";
char MsgSize=(char) malloc (sizeof(char) * 5); memset(MsgSize,0,5);
int DontCare;
DontCare=sprintf(MsgSize, "%d", PtrPayloadBuffer->size());

(PtrHeaderBuffer).clear();
(
PtrHeaderBuffer).append(Part1);
(PtrHeaderBuffer).append("10.1.1.100"); // don't know how to encode IP Addr as string
(
PtrHeaderBuffer).append(Part2);
(PtrHeaderBuffer).append(MsgSize);
(
PtrHeaderBuffer).append(Part3);
}

int main(int argc, char * argv[])
{
// Build socket to remote server 10.1.1.100

BuildPayload(PtrPayloadBuffer, AppName, L4Proto, L4Port);
BuildHeader(PtrHeaderBuffer, PtrPayloadBuffer, RemoteServer);
HeaderBuffer.append(PayloadBuffer);

// Write string HeaderBuffer to socket, then close

return 1;
}[/CODE]

Hmmmmm... If that's the case, I wonder where I need to go to figure out which libraries I need...

Hi everyone,

I have a "This should be simple!" kind of problem. I need to do a little socket programming on a SunOS machine. I went back to an old school assignment I did years ago, cut-n-pasted that code, intending to basically cannibalize it for the program I need to write now. Trouble is, my compiler chokes on the socket-specific terms like getaddrinfo() or inet_ntop.

Here is the output when I try to compile:

[CODE]bash-3.00$ g++ Main.cpp
Undefined first referenced
symbol in file
getaddrinfo /var/tmp//ccCpuGRv.o
freeaddrinfo /var/tmp//ccCpuGRv.o
inet_ntop /var/tmp//ccCpuGRv.o
gai_strerror /var/tmp//ccCpuGRv.o
ld: fatal: Symbol referencing errors. No output written to a.out
collect2: ld returned 1 exit status
bash-3.00$ [/CODE]----------------------------------------------------------------------------

I'll post the latest code I'm using, but I don't think my problem lies in the code. I've tried compiling my own code plus about a dozen examples I've found online. I [I][B]ALWAYS[/B][/I] get the same problem, this [I]"undefined symbol"[/I] problem with some socket-specific terms. I've also tried alternating between g++ and gcc; both compilers essentially complain about the same "undefined symbol" problem.

(As a side note, I can copy the EXACT SAME CODE over to my school's Linux machine, and it compiles just fine there!)

So I'm thinking this is (A) a problem with the SunOS machine I'm working on, or (B) I am forgetting a library or something. I'm hoping it is not (A), as I'm not the system admin and don't have the power to install anything on this platform.

Has anyone seen something like this? I ...

Hi folks,

General question here... I'm writing a program which reads a ton of source data, crunches the numbers, and outputs a few nice summary reports. The source data is a lot of individual records:

[B]00001,Item1,Item2,Item3,Item4,Item5,...
00002,Item1,Item2,Item3,Item4,Item5,...
00003,Item1,Item2,Item3,Item4,Item5,...[/B]

Originally, I created an object called "Record," which stored each Item. But I ran into serious trouble when I realized there are literally [B][I]MILLIONS[/I][/B] of records. My machine simply doesn't have enough system memory to handle the load. So I need a completely new approach to this problem.

Someone mentioned to me that my program should learn about these records by creating a hash table on-the-fly. Okay, sounds great. So I read up about hash tables in general and C++'s map function in particular, but I don't see a direct way to use these to address my problem. A hash table/map function would seem great if you wanted to track large amount of data which seperates into two items of information (person's name and phone number, for example.) What do you do when you have ten, twenty, maybe more thirty items of information you need to track?

So I'm just generally asking... does anyone see a way to do what I'm trying to do? I'm just asking for some general brainstorming ideas...

     Many thanks!

Awesome, thanks a million! I think you're right, I think this must be a memory problem. I'll retool the code to make sure I'm not littering the stack...
Many thanks!

HmmMMMmmmm... Okay, that's good to know. I don't have any experience with hex editors, but I suppose today's a good day to learn. :)

I'll look into that catch{} statement...

Hi everyone,

I'm a moderately experienced C++ programmer working on code which must do the following:
(a) Import data from a lot of little CSV files
(b) Load that data into various objects
(c) Do stuff with that data

The code I've written does (a), (b), and (c) pretty well, but I've noticed a problem with (a), which I want to ask you guys about.

Suppose I have 1000 source files. My program successfully processes Files #1 through #500. But when it reaches File #501, my program chokes and seg faults, and I automatically lose [I][B]ALL[/B][/I] the data I've collected. This is a big problem, because there is a LOT of data to process. It may take me three or four hours just to reach File #500.

When the program reads a file, each individual line is loaded into a string called [B][COLOR="Red"]Line[/COLOR][/B], which is then parsed for individual values. If I'm reading gdb right ([I]output below[/I]), the parsing is causing the trouble. ([I]Lines 15 & 16, below[/I]) As for the line in the file which is causing the trouble, I don't see any format problems with the line itself. When I run the program multiple times, it is the same exact line which causes the seg fault every time.

What would be awesome would be a way to tell the program, [I]"if you see a line which confuses you, skip that line, don't just automatically crash!"[/I] Skipping the entire file would be okay too.

Below is the code I'm ...

Outstanding! Thank you so much, this is exactly what I hoped for! :)

Hi everyone,

I'm a relative beginner to writing UNIX scripts. In the past, I've been able to hack together simple scripts. Now I need a script which a little more complex than I'm used to, and I really need help. I'm up against a tight deadline and am growing desperate, as I can't seem to find a solution either on the web nor in my UNIX programming book.

Here's the problem: I'm on a SunOS system. On the machine, I have a large number of files scattered across a vast directory structure. I have to copy all those target files into my home directory. Luckily, the directory structure is well-organized. It looks like this:

   [B]/root/projects/*ARCHIVE*/date/*SUBARCHIVE*/output/*SUBSUBARCHIVE*/[COLOR="Red"]The_Files_I_Need[/COLOR][/B]

The directories in lowercase have constant names - I don't have to worry about them ever changing. But the directories I've named with ALLCAPS do change names. Think of them as wild cards.

Put another way: If I wanted to exhaustively list every directory, the top tier would looks like this:

[B][I]/root/projects/PROJECT01/
/root/projects/PROJECT02/
/root/projects/PROJECT03/
/root/projects/PROJECT04/
...
/root/projects/PROJECT20/[/I][/B]

The next tier would look like this:

[B][I]/root/projects/PROJECT01/date/JAN2000/
/root/projects/PROJECT01/date/FEB2000/
/root/projects/PROJECT01/date/MAR2000/
...
/root/projects/PROJECT01/date/MAY2010/
/root/projects/PROJECT02/date/JAN1995/
...
/root/projects/PROJECT20/date/DEC2005/[/I][/B]

And the next tier would look like this:

[B][I]/root/projects/PROJECT01/date/JAN2000/output/SAMPLE0001/
/root/projects/PROJECT01/date/JAN2000/output/SAMPLE0002/
/root/projects/PROJECT01/date/JAN2000/output/SAMPLE0003/
...
/root/projects/PROJECT01/date/JAN2000/output/SAMPLE1328/
...
/root/projects/PROJECT20/date/DEC1995/output/SAMPLE483822/[/I][/B]

And so on. The target files I ultimately need to read are in those final directories.

[B][I]/root/projects/PROJECT01/date/JAN2000/output/SAMPLE0001/[COLOR="Red"][COLOR="Red"]TARGET_102932[/COLOR][/COLOR]
/root/projects/PROJECT01/date/JAN2000/output/SAMPLE0001/[COLOR="Red"]TARGET_32323[/COLOR]
/root/projects/PROJECT01/date/JAN2000/output/SAMPLE0001/[COLOR="Red"]TARGET_32999293[/COLOR]
...[/I][/B]

There are literally thousands of these target files, all with dynamic names.

So the problem I'm having is I can't just do a "cp /root/projects//date//output//" because the pathnames ...

Hi everyone,

Thanks for taking a look at this - I got a private reply explaining an efficient solution. (going to do the array as a global variable instead of an object) Thanks for your help!
-P

Shoot, didn't make a difference to change the "char *" to "string"'s. Oh well...
-Pete

[QUOTE=daviddoria;1207758]I didn't look closely, but my first thought is to try std::vector<std::string> - is there a reason you need it to be std::vector<char*> ?

Dave[/QUOTE]

Hi Dave,

No, no reason, I've always thought that using "char *" was more precise and less error-prone than "string." I'll try your suggestion and see what happens...

Thanks!
-Pete

Hi everyone,

I'm a moderately experienced C++ programmer and a network engineer. I’m having a weird problem with using an array of vector<char *>, which I’ve never tried to work with before. I’m working on a program which does the following:

  1. Inputs and parses a file called [B]PREFIX_FILE[/B], which contains all the prefix information on my network.
  2. For every line, extracts the first token as a string and the second as an int. The value that int will always be from 0 to 32. (33 total)
  3. The program creates an object called [B]MaskObject[/B], which is essentially just an array of 33 [B]vector<char *>[/B]’s.
  4. For each string read from the file, the program stores the string into the corresponding vector. [I](For example, strings “10.10.10.0”, “20.20.20.0”, and “30.30.30.0” should be stored into vector 22 in the MaskObject; string “40.40.40.0” should be stored into vector 30, and “50.50.50.0” and “60.60.60.0” should be stored into vector 32.)[/I]

All of this seems to work just fine, except for Step 4. The funny thing is when the program completes, the correct number of strings are stored in the correct vectors… but all the strings have the same value of the last string only!!! [I](i.e., all stored strings are “60.60.60.0” and I lose the values of the first five strings.)[/I]

I can’t figure this out. My first instinct was all strings were being stored correctly, but my “THEArrayDisplay()” function must be printing out only the last string value. But I’ve carefully checked, and ...

Nice! This is great advice, I really appreciate your help. This solves a lot of problems for me! :)

Many thanks!
-Pete

Hello everyone,

I’m an intermediate-level C++ programmer grappling with a fairly rudimentary problem. I’m creating a C++ object called FruitCart; FruitCart contains a number of integers categorizing the numbers of individual fruit in the cart. I also need FruitCart to contain accessor functions so other functions can set, retrieve, and print the fruit values. Here’s what I have so far:

[code]

class FruitCart {
public:
// Constructors
FruitCart();
~FruitCart();

// Accessors
void SetApples(int a)  {Apples=a;}
int GetApples()        {return Apples;}
void PrintApples()     {cout<<Apples;}

// Need accessor functions like the above for all kinds of fruit

protected:
int Apples; // Number of Apples in the cart
int Oranges; // Number of Oranges in the cart
int Bananas; // Number of Bananas in the cart
int Plums; // Number of Plums in the cart

// May have nearly 50 kinds of fruit!
};

[/code]

The problem I have is that I may have over fifty kinds of fruit in the cart! It would be a big pain to manually write out accessor functions for each kind of fruit.

I’m searching for a more intelligent solution. What I’d like to have is a general accessor function where I pass in the name of the fruit as a string (specifically, as a char * pointer) and leave everything else the same. Put in quasi-psuedocode:

[code]

class FruitCart {
public:
// Constructors
FruitCart();
~FruitCart();

// Accessors
void SetFruit(int a, char * FruitType)
int GetFruit(char * FruitType)
void PrintFruit(char * FruitType)

protected:
int Apples; ...