GIDForums  

Go Back   GIDForums > Computer Programming Forums > C++ Forum
User Name
Password
Register FAQ Members List Calendar Search Today's Posts Mark Forums Read

 
 
Thread Tools Search this Thread Rate Thread
  #1  
Old 08-Mar-2005, 17:36
jheron jheron is offline
New Member
 
Join Date: Feb 2005
Posts: 23
jheron is on a distinguished road
Question

Help with const?


Hello I have written an app like the one in my previous post only I am using a structure instead of parallel arrays and I have tried to implement the things I am learning here :-D I have a few errors like I had in the begining with the prev app. and I would like to address them here:
CPP / C++ / C Code:
// dynamic mem using a struct
//will collect names and ages of people and display them and their 
//averag age weee....

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

struct pplPtr			//structure to gather name age and sex
{
	char *name[20];
	int age;
	char *sex[2];
};

int setMem(pplPtr *people[], const int numPpl);
void getInput(pplPtr *people[], const int numPpl);
float getAvg(pplPtr *people[], const int numPpl);
void display(pplPtr *people[], const int numPpl, const int avg);

int main()
{
	int num = 0;
	float avg;

	cout << "How many people do you want to add?(50 max!)" << endl;	//sets the num of entries
	cin >> num;
	if(num > 50 || num <=0){			//check input
		cout << endl << "oops thats not rite :)" << endl;
		return 0;}

	const int numPpl = num;		// this to try and fix the error "expected constant expression"
								//   ... it didnt work 				
	pplPtr *people[numPpl];

		if(!setMem(people, numPpl)){		// allocate mem
			return 0;}						// exit if err
	getInput(people, numPpl);				// fills structures
	avg = (getAvg(people, numPpl));			// calcs average age
	display(people, numPpl, avg);				// hmmm....
	return 0;
}
//*************************************************************************************
int setMem(pplPtr *people[], const int numPpl)	//Sets up the dynamic mem for the
{												//structures data 
	int i;

	for(i=0; i<numPpl; i++)
		{
			people[i] = new pplPtr;
			if(!people[i]){						// return mem error to main 
				cout << endl << endl << "mem allocation failed at " << i << endl;
				return 0;}
	}
	return 1;
}
//**************************************************************************************
void getInput(pplPtr *people[], const int numPpl)
{
	int i;
	string buffer;

	for(i=0; i<numPpl; i++)
	{
		cin.ignore(80,'\n'); // skip rubbish
		cout << endl << "What is person number " << (i+1) << "'s name? ";	//gets name
		getline(cin, buffer);
		if(buffer.length() > 19){							
			buffer.erase (19);}
		strcpy(people[i]->name, buffer.c_str());

		cout << endl << (people[i]->name) << "'s age? ";	// gets age		
		cin >> people[i]->age;
		
		cout << endl << "and "<< (people[i]->name)<< "'s sex (M or F)? ";	//gets sex ... :)
		getline(cin, buffer);
		if(buffer.length() > 1){
			buffer.erase(2);}
		strcpy(people[i]->sex, buffer.c_str());
	}
	cout << endl << '\a';
	return;
}
//***************************************************************************************
float getAvg(pplPtr *people[], const int numPpl)	
{
	int i, total = 0;
	float avg;

	for(i=0; i<numPpl; i++)
	{
		total += people[i]->age;
	}
	avg = (total/numPpl);
	return avg;
}
//***************************************************************************************
void display(pplPtr *people[], const int numPpl, const int avg)
{
	int i;

	cout << "\t" << setfill(' ') << setw(8) << " " << setw(12) << left << "Name"
		<< setw(5) << right << "Age"
		<< setw(5) << " " << setw(5) << right << "Sex" << endl;
    cout << "\t" << setfill('_') << setw(35) << "_" << endl;
	
	for(i=0; i<numPpl; i++)
	{
		cout << "\t" << setfill(' ') << setw(20) << left << (people[i]->name)
			<< setw(5) << right << (people[i]->age)
			<< setw(5) << " " << setw(5) << right << (people[i]->sex) << endl;
	}
	cout << endl <<"The peoples average age is " << avg << '!' << endl;
	return;
}

And here are the errors reported by my visual c++ 6 compiler:
Code:
--------------------Configuration: dynmemwithstruct - Win32 Debug-------------------- Compiling... dynmemwithstruct.cpp error C2057: expected constant expression error C2466: cannot allocate an array of constant size 0 error C2133: 'people' : unknown size error C2664: 'strcpy' : cannot convert parameter 1 from 'char *[20]' to 'char *' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast error C2664: 'strcpy' : cannot convert parameter 1 from 'char *[2]' to 'char *' dynmemwithstruct.exe - 5 error(s), 0 warning(s)
I think once I can figure out the first error I will be good to go ... mabie
the error refers to this "pplPtr *people[numPpl];" line. Why wont this work? I even tried to make numPpl a constant as you can see with the lines above it but that didnt work either? If I make numPpl a const global and assign a value to it no probs but I want the user to determin the numPpl!
As allways any and all help is greatly appreciated!
sincerely Jon
  #2  
Old 08-Mar-2005, 22:18
WaltP's Avatar
WaltP WaltP is offline
Outstanding Member
 
Join Date: Feb 2004
Location: Midwest US
Posts: 3,242
WaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to allWaltP is a name known to all
You'll have to tell us where the errors are. With over 100 lines of code we can't tell what line error C2057: expected constant expression refers to. Place comments in the code pointing out the lines. And you might want to just post the code section (8-20 lines maybe) instead of 117 lines that don't have any bearing on the problem.
__________________

Age is unimportant -- except in cheese
  #3  
Old 09-Mar-2005, 01:40
LuciWiz's Avatar
LuciWiz LuciWiz is online now
Moderator
 
Join Date: Jul 2004
Location: Cluj-Napoca (Romania)
Posts: 889
LuciWiz is a jewel in the roughLuciWiz is a jewel in the roughLuciWiz is a jewel in the roughLuciWiz is a jewel in the rough
I spoted this:

Quote:
Originally Posted by jheron
CPP / C++ / C Code:
const int numPpl = num;    // this to try and fix the error "expected constant expression"
                //   ... it didnt work    

I see you got the problem here:

Quote:
Originally Posted by jheron
CPP / C++ / C Code:
pplPtr *people[numPpl];

But this wasn't the solution.

The problem is that your compiler doesn't like the idea about reserving a static area of memory without knowing it's size. 'Cause it can't.
Now if you gave a constant expression, like 5, he would have been OK with it.
To accomplish this you need dynamic memory allocation.

CPP / C++ / C Code:
	int numPpl = 5;
	pplPtr * people = new pplPtr[numPpl];
	
	if ( people != NULL )
	{
		//...
	}

	delete [] people;
	people = NULL;

Or to keep your model of pointer to pointer (although I'm not sure why you needed this in this context):

CPP / C++ / C Code:
	int numPpl = 5;
	pplPtr ** people = NULL;
	people = new (pplPtr * [numPpl]);

Here is a lame example:

CPP / C++ / C Code:
	int numPpl = 5;
	pplPtr ** people = NULL;
	people = new (pplPtr * [numPpl]);
	
	if ( people != NULL )
	{
		for ( int i = 0; i < numPpl; i++ )
		{
			people[i] = new pplPtr[2];
			if ( people[i] != NULL )
			{
				people[i][0].age = 0 + i;
				people[i][1].age = 1 + i; // my imagination is on vacation
			}
		}

		for ( int i = 0; i < numPpl; i++)
		{
			if ( people[i] != NULL )
			{
				cout << "people[" << i << "][0].age " << people[i][0].age
				<<  "\tpeople[" << i << "][1].age " << people[i][1].age << std::endl;
			}
		}
	}	


	for ( int i = 0; i < numPpl; i++ )
	{
		if ( people[i] != NULL )
		{
			delete [] people[i];
			people[i] = NULL;
		}
	}

	if ( people != NULL )
	{
		delete [] people;
		people = NULL;
	}

You should read the C way and a more comprehensive explanation here.

Also, if you will follow Walt's indication, you'll make it easy on us to provide you with faster and better help.

Kind regards,
Lucian
__________________
Please read these Guidelines before posting on the forum

"A person who never made a mistake never tried anything new."
Einstein
  #4  
Old 10-Mar-2005, 18:37
jheron jheron is offline
New Member
 
Join Date: Feb 2005
Posts: 23
jheron is on a distinguished road
Thanks for your help guys!!
Sorry for the delay I have had way too much on the go as of late!
Hey walt, sorry I wont post the whole thing again but I did mention where the problem was in the post. I will coment the code from now on

LuciWiz I think I am in over my head with the c++ let alone C lol.
I figured I could let the user the input the number of structures required and its asociated memory with out any coding wizardry lol I think I will just use a const global for now untill I can wrap my sparse head around this stuff a little more
Well I can get the code to compile now using a static but there is still somthing fishy going on with my mem usage it will prompt for the first name and then crash on enter? I think it is still somthing to do with my input routine?
CPP / C++ / C Code:
void getInput(pplPtr *people[], const int numPpl)
{
	int i;
	string buffer;

	for(i=0; i<numPpl; i++)
	{
		//cin.ignore(80,'\n'); // skip rubbish
		cout << endl << "What is person number " << (i+1) << "'s name? ";	//gets name
		getline(cin, buffer);
		if(buffer.length() > 19){							
			buffer.erase (19);}
		strcpy(*people[i]->name, buffer.c_str()); // <- mabie problem?

		cout << endl << (people[i]->name) << "'s age? ";	// gets age		
		cin >> people[i]->age;
		
		cout << endl << "and "<< (people[i]->name)<< "'s sex (M or F)? ";	//gets sex ... :)
		getline(cin, buffer);
		if(buffer.length() > 1){
			buffer.erase(2);}
		strcpy(*people[i]->sex, buffer.c_str()); /// Could this be the problem? the pointer? its the only way I coud get it to compile
	}
	cout << endl << '\a';
	return;
}
I have a sucpition that this line "strcpy(*people[i]->name, buffer.c_str());" may be the problem I dont know why I need people to be a pointer if I don't add the pointer notation I get this error:
Code:
error C2664: 'strcpy' : cannot convert parameter 1 from 'char *[20]' to 'char *' Types pointed to are unrelated; conversion requires reinterpret_cast, C-style cast or function-style cast
I dont understand what it means "unrelated" shouldn't this copy the buffer.c_str() (which I am assuming just adds the null 0 at the end of the string?) to the member of people name?
Thanks for any and all help guys I know eventualy there will be an audible click in my head and I will see the big picture here
Sincerely Jon
  #5  
Old 10-Mar-2005, 20:24
jheron jheron is offline
New Member
 
Join Date: Feb 2005
Posts: 23
jheron is on a distinguished road
Lightbulb

AHHA! I figured it out I had pointers in the srtructure I also found a way that works better for me than that buffer was that I was using. I know there is no error control on the people->sex but I just didn't write any I was happy to finaly get it going now onto the next chapter
Well here is the finished working code if any one other than me is learnig from this post is interested
CPP / C++ / C Code:
// dynamic mem using a struct
//will collect names and ages of people and display them and their 
//averag age weee....

#include <iostream>
#include <iomanip>
#include <string>

using namespace std;

struct pplPtr			//structure to gather name age and sex
{
	char name[20];
	int age;
	char sex[2];
};

const int big = 100;			// 

int setMem(pplPtr *people[], const int numPpl);
void getInput(pplPtr *people[], const int numPpl);
float getAvg(pplPtr *people[], const int numPpl);
void display(pplPtr *people[], const int numPpl, const int avg);
void freeMem(pplPtr *people[], const int numPpl);

int main()
{
	int numPpl = 0;
	float avg;

	cout << "How many people do you want to add?(100 max!)" << endl;	//sets the num of entries
	cin >> numPpl;
	if(numPpl > 50 || numPpl <=0){			//check input
		cout << endl << "oops thats not rite :)" << endl;
		return 0;}

	pplPtr *people[big];

		if(!setMem(people, numPpl)){		// allocate mem
			return 0;}						// exit if err
	getInput(people, numPpl);				// fills structures
	avg = (getAvg(people, numPpl));			// calcs average age
	display(people, numPpl, avg);				// hmmm....
	freeMem(people, numPpl);
	return 0;
}
//*************************************************************************************
int setMem(pplPtr *people[], const int numPpl)	//Sets up the dynamic mem for the
{												//structures data 
	int i;

	for(i=0; i<numPpl; i++)
		{
			people[i] = new pplPtr;
			if(!people[i]){						// return mem error to main 
				cout << endl << endl << "mem allocation failed at " << i << endl;
				return 0;}
	}
	return 1;
}
//**************************************************************************************
void getInput(pplPtr *people[], const int numPpl)
{
	int i;
	string buffer;

	for(i=0; i<numPpl; i++)
	{
		cin.ignore(80,'\n'); // skip rubbish
		cout << endl << "What is person number " << (i+1) << "'s name? ";	
		cin.get(people[i]->name, 20);		// works well for char string input :)
		cout << endl << (people[i]->name) << "'s age? ";			
		cin >> (people[i]->age);
		
		cout << endl << "and "<< (people[i]->name)<< "'s sex (M or F)? ";	//gets sex ... :)
		cin >> (people[i]->sex);
		cout << endl;
		
	}
	cout << endl << '\a';
	return;
}
//***************************************************************************************
float getAvg(pplPtr *people[], const int numPpl)	
{
	int i, total = 0;
	float avg;

	for(i=0; i<numPpl; i++)
	{
		total += people[i]->age;
	}
	avg = (total/numPpl);
	return avg;
}
//***************************************************************************************
void display(pplPtr *people[], const int numPpl, const int avg)
{
	int i;

	cout << "\t" << setfill(' ') << setw(8) << " " << setw(12) << left << "Name"
		<< setw(5) << right << "Age"
		<< setw(5) << " " << setw(5) << right << "Sex" << endl;
    cout << "\t" << setfill('_') << setw(35) << "_" << endl;
	
	for(i=0; i<numPpl; i++)
	{
		cout << "\t" << setfill(' ') << setw(20) << left << (people[i]->name)
			<< setw(5) << right << (people[i]->age)
			<< setw(5) << " " << setw(5) << right << (people[i]->sex) << endl;
	}
	cout << endl <<"The peoples average age is " << avg << '!' << endl;
	return;
}
//**********************************************************************************
void freeMem(pplPtr *people[], const int numPpl)
{
	int i;

	for(i=0; i<numPpl; i++)
	{
		delete people[i];
	}
	cout << "Mem freed :)" << endl << endl;
	return;
}

Thanks every one for there help
sincerely Jon
 
 

Recent GIDBlogFlickr uploads of IA pictures by crystalattice

Thread Tools Search this Thread
Search this Thread:

Advanced Search
Rate This Thread
Rate This Thread:

Posting Rules
You may not post new threads
You may not post replies
You may not post attachments
You may not edit your posts

vB code is On
Smilies are On
[IMG] code is On
HTML code is Off
Forum Jump

Similar Threads
Thread Thread Starter Forum Replies Last Post
I need help implementing kjc_13 C++ Forum 0 14-Feb-2005 16:00
template comiling problems - need expert debugger! crq C++ Forum 1 01-Feb-2005 21:26
My program can run,but warning were display on Vc++ fwongmc C Programming Language 5 08-Dec-2004 10:15
Error: (function) undeclared -first use of this function crystalattice C++ Forum 6 01-Nov-2004 04:36
hashing help saiz66 C++ Forum 1 06-Jul-2004 06:16

Network Sites: GIDNetwork · GIDWebHosts · GIDSearch · Learning Journal by J de Silva, The

All times are GMT -6. The time now is 04:35.


vBulletin, Copyright © 2000 - 2008, Jelsoft Enterprises Ltd.