MattyRobot 22 Junior Poster in Training

here is what I came up with:

the problems I fixed:

  • you were trying to delete the cptr array itsself. not the things inside it, so I added a loop to do this
  • array values start at 0 so I changed some loops or you would get segmentation faults trying to access the item above the one you wanted (eg 2 items you would have instead of 0 and 1, printed item 1 and 2 (and 2 would not exist!!))
  • maybe not necessarily, but I added memsets to make sure the string terminates (if its filled with rubbish it may think its longer than it actually is)
  • removed system("pause") in favour of cin.get() (does the same thing but cin.get() is less resource heavy ect..)

this now compiles ok with minGW and runs fine for me. see if it works for you.

#include<iostream>
#include<cstring>

using namespace std;


class city
{
      protected:

		char *name;
		int len;

      public:
			void getname(void)
			{
				char *s;
				s= new char[30];
				memset(s, '\0', sizeof(char) * 30);
				cout<<"Enter city name: ";
				cin>>s;
				len= strlen(s);
				name= new char[len+1];
				strcpy(name,s);
			}
			void printname()
			{
				cout<<name<<"\n";
			}
};
int main()
{
    city *cptr[10];
    int n = 0;
    int option;
    do
    {
        cptr[n]= new city;
        cptr[n]->getname();
        n++;
        cout<<"Do you want to enter one more name?\n";
        cout<<"(Enter 1 for yes 0 for no):";
        cin>>option;
	}
	while(option);

    cout<<"\n";

    for(int i=0; i<n; i++)
    {
		cptr[i]->printname();
	}

	for(unsigned short i = 0; i < n; ++i)
	{
		delete cptr[i];
	}

        
	cout<< "\npress …
MattyRobot 22 Junior Poster in Training

this is an idea I had. remove everything above 0 like you did. then convert the decimal bit to a string. then get the length of the string.

#include <iostream>
#include <string>
#include <sstream>

int DecimalPlaces(double test)
{
	double JustDecimals = test - (int) test;

	std::stringstream converter;

	converter<< JustDecimals;

	std::string StringForm(converter.str());

	return StringForm.length() - 2 /* -2 characters for the 0. */;

}

int main()
{
	std::cout<< "decimal places in " << 0.235987 << " " << DecimalPlaces(0.235987);
        // returns 6 which is right
}

this works but it does not test exceptions like if the input is not a decimal then dont minus the 2 otherwise DecimalPlaces(3) == -2

oh and the maximum number of decimal places seems to be 6 (with one number to the left of the decimal point).

MattyRobot 22 Junior Poster in Training

as I said i am new to classes, with a few minutes of tinkering I moved the implamentation of pet.edit() to after the function declarations and the class to above the functions but below the global variables. that is a better way though, I will change it. thanks for teaching me something
:)

tux4life commented: Thanks for using code tags, and for being nice :) +22