Thread: why doesn't work

  1. #1
    Registered User
    Join Date
    Apr 2005
    Posts
    18

    Unhappy why doesn't work

    hi
    i try to make a dynamic array inside a loop but i have a problem
    i want restore each time in the loop a name and print it out the delete the array the the loop go on the add other name the print it then delete it .....
    but it didn't work with me , any idea?
    here is my code:

    i try to creat dynamic name inside a loop but/....!
    Code:
    i try to creat dynamic name inside a loop but/....!
    int main()
    {
    char *names = NULL;
    for (int i=0; i<3; i++)
    {
    if(names)
    {
    cout<<"yes"<<endl;
    delete[]names;
    names=NULL;
    }
    cout << "1- Enter the name : ";
    names=new char [size];
    cin.get (names , size);
    char k;
    do
    {
    cin.get(k);
    }while(k!='\n');
    cout<<names;
    }
    return 0;
    }

  2. #2
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    So what compiler errors (if any) do you get? Or what's the problem if it compiles fine?

    I don't see any problems besides 'size' being undeclared.
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

  3. #3
    Registered User
    Join Date
    Apr 2005
    Posts
    22
    maro, do you have to use char* to store the name? If not, it would be a lot easier to use std::string instead.
    Also, if you have to use an array, there is no need to delete the array, just overwrite what's in it each time. Or if you really want to delete it, do it at the bottom of the loop. I think the code doesn't compile though because youre using cin in a wrong way.
    Here is what i would do:
    Code:
    #include <iostream>
    #include <string>
    
    int main(int argc, char *argv[]) {
      using namespace std;
    
      std::string names = "";
       for (int i=0; i<3; i++)
      {
        cout << "1- Enter the name : ";
        cin>>names;
        cout<<names<<"\n";
      }
    
      return 0;
    }
    Oh yes, and the size is undeclared
    Last edited by anykey; 04-20-2005 at 04:38 PM.

  4. #4
    Registered User
    Join Date
    Apr 2005
    Posts
    18

    hey

    first i would like to thank you for answring my Q

    My code is a part of a class Car

    in the main i need to creat an array with objects ..
    3 objects need to be created
    so 3 different names for 3 cars

    and about using std :: string , i can't use it coz still i didn't see it at the school

    ,, the error is the the first time the loop executing it asks the name so no problem then i delete the name Dynamic array to creat a new one with a new name
    then the loop will excuting the second time but i can't add the second name ..... any idea

    sorry for my bad english

  5. #5
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    It seems to work fine for me (with the definition of 'size'). You might be trying to enter a string that is too long, however. Try changing input code so that it checks for invalid input:
    Code:
    //change this
    /*
    cin.get (names , size);
    char k;
    do
    {
    cin.get(k);
    }while(k!='\n');
    */
    //to this
    if (!cin.getline (names , size))//use getline so it removes the '\n'
    {                                           //(getline returns the stream state)
      cout<<"Invalid input";
      cin.clear();
      cin.ignore(numeric_limits<int>::max(),'\n');
    }
    Also, make sure 'size' is a large enough value to hold a name.

    Actually, re-reading your post, it sounds like you might want to store three names at once, in which case you would need an array of char* and you wouldn't want to delete after each loop...

    Edit: You will also need to #include <limits> to use the numeric_limits class
    Last edited by JaWiB; 04-20-2005 at 05:32 PM.
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

  6. #6
    Registered User
    Join Date
    Apr 2005
    Posts
    18
    hi JaWiB
    thank you very much for your help but:
    i just start with c++ and all what you said is very Difficult for me ..
    and the size in my header file is 100
    look let me do it more easly :


    if i ask you to creat a pointer that point to Dynamic array.
    now creat for loop that will execute 3 times.
    ***************************************
    the first time you will creat the dynamic array and the pointer will point to it.
    then the user will add a name inside this array.
    then clean the buffer
    then print out this name.
    then delete this dynamic array and let the pointer point to NULL
    **************************************
    the for loop will execute the second time
    will creat the new dynamic array and the pointer will point to it.
    and ........etc
    ***********************************
    is it possible to creat this?
    coz as i told you im just a beginner .
    thanks

  7. #7
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    What you posted works fine for me. Maybe post your whole source file. Like I said, from what I see, it should work...
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

  8. #8
    Registered User
    Join Date
    Apr 2005
    Posts
    18
    ok here is my code

    1st Header file :
    Code:
    #ifndef __dclass_h
    #define __dclass_h
    
    const int size =50;
    void  clearBuf();
    void menu();
    
    class Car
    {
    	private:
    		int   _nr_parts;
    		int    _hp;
    		float *_parts;
    		char  *_brandname;
    		
    
    	public:
    		 Car  (void);
    		 Car  (int hp, float *parts, int nr_parts, const char *name);
    		~Car  (void);
    
    		void  set_hp (int hp);
    		int   get_hp (void)const;
    
    		void  set_brandname (const char *name);
    		char  get_brandname ()const;
    
    		void  set_Car (int hp,float *parts,int nr_parts, const char *brandname);
    
    		void  print_car (void)const;
    
    		void  add_part (int part_nr);
    		void  remove_part (int part_nr);
    
    		void  add_parts    (float *part_nrs, int nr_parts);
    		void  remove_parts (float *part_nrs, int nr_parts);
    
    };
    
    #endif
    2nd CPP file:
    Code:
    #include "D_class.h"
    #include <iostream>
    #include <cstring>
    
    using namespace std;
    
    void  clearBuf()  // this function to clear the buffer
    {
    	char k;
    	do
    	{
    		cin.get(k);
    	}while(k!='\n');
    }
    
    Car::Car  () //defualt constructor
    {
    	 _nr_parts  = 0;
    	 _hp        = 0;
    	 _parts     = NULL;
    	 _brandname = NULL;
    	
    }
    
    Car::Car  (int hp, float *parts, int nr_parts, const char *name) 
    {
    	_hp         = 0;
    	_parts     = NULL;
    	_brandname = NULL;
    	_nr_parts  = 0;
    	set_Car(hp,	parts, nr_parts, name);
    	
    }
    
    Car::~Car  (void) //destructor
    {
    		cout<<"Destructor****"<<endl;
    		if(_parts)
    		{
    			delete[]_parts;
    			_parts=NULL;
    			cout << "Dynamic parts deleted.."<<endl;
    		}
    		
    		if(_brandname)
    		{
    			delete[]_brandname;
    			_brandname=NULL;
    			cout << "Dynamic name deleted.."<<endl;	
    		}
    		else
    		{
    			cout<<"something wrong"<<endl;
    		}
    	
    }
    
    //Set functions
    
    void Car::set_hp (int hp)
    {
    	_hp = hp;
    }
    
    void Car::set_brandname (const char *name)
    {
    	int length = strlen(name)+1; 
    	_brandname = new char [length];
    	strcpy(_brandname,name);
    }
    
    void Car::add_part (int part_nr)
    {
    	_nr_parts = _nr_parts + part_nr;
    }
    
    void Car::remove_part (int part_nr)
    {
    	if(_nr_parts>part_nr)
    	{
    		_nr_parts = _nr_parts - part_nr;
    	}
    	else
    	{
    		cout<< "you will remove all parts"<<endl;
    		_nr_parts=0;
    	}
    		
    }
    
    
    void Car::add_parts    (float *part_nrs, int nr_parts)
    {
    	if (part_nrs)
    	{
    			cout << "What is the cost of the new parts ? "<<endl;
    					for(int m=0;m<nr_parts ; m++) // add values into the array
    					{
    						cout << "Part nr ("<<m+1<<") costs : ";
    						cin  >> *(part_nrs+m);
    					}	
    		//Step 1 call add part function to set the length of the all array
    		add_part (nr_parts);
    
    		//Step 2 creat temp array to store the 2 arrays
    		float *temp = new float [_nr_parts];
    		if (temp)
    		{
    			if (_parts)
    			{
    					cout<<"\nThis nooooooooooooooooooooo work";
    					for (int k=0; k< (_nr_parts); k++)
    				{
    					*(temp + k) = *(_parts + k);
    				}
    
    				for (int j = (_nr_parts - nr_parts) ; j<(_nr_parts) ; j++)
    				{
    					*(temp + j) = *(part_nrs+j);
    				}
    			}
    		
    			else if (_parts == NULL)
    			{
    					cout<<"\ntest that _part point to NULL"<<endl;
    				for (int m=0; m< _nr_parts; m++)
    				{
    					*(temp + m) = *(part_nrs+m);
    				}
    			}
    			delete []_parts;
    			_parts=temp;
    		}
    		else
    			cout<<"no temp created"<<endl;
    	}
    	else 
    		cout<<"no Dynamic array created... "<<endl;
    	
    }
    
    
    void Car::remove_parts (float *part_nrs, int nr_parts)
    {
    	cout<<"Remove Function"<<endl;
    	if (part_nrs)
    	{
    			cout<<"\ntest if i pass D array"<<endl;
    		// the following part is to store what will be removed
    		if (_nr_parts>0)
    		{
    				for (int k=(_nr_parts-nr_parts-1); k<nr_parts; k++)
    				{
    						*(part_nrs+k)=*(_parts+k);
    						cout<<"Part nr("<<k+1<<") with price of <"<<*(part_nrs+k)<<">will be remove"<<endl;
    				}
    				
    		}
    		else
    		{
    			cout<<"there is no items to be remove.....!!!!!"<<endl;
    			delete[]_parts;
    		}
    
    		// now start remove the parts
    		remove_part (nr_parts);
    		if (_nr_parts>0) // to test if the user doesn't wants to remove all parts
    		{
    			float *temp = new float [_nr_parts];
    			for (int i=0; i<_nr_parts; i++)
    			{
    				*(temp+i)=*(_parts+i); 
    			}
    			delete []_parts;
    			_parts=temp;
    		}
    		else
    		{
    			cout<<"all parts have been removed"<<endl;
    			delete []_parts;
    			_parts=NULL;
    		}
    	}
    	else
    		cout<<"no Darray have pased"<<endl;
    }
    
    void Car::set_Car (int hp, float *parts,int nr_parts, const char *brandname)
    {
    	set_hp(hp);
    	set_brandname(brandname);
    	add_parts (parts,nr_parts);
    	print_car();
    }
    
    
    
    void menu()
    {
    	cout << "choose .."<<endl;
    	cout << "1 - Add part "<<endl;
    	cout << "2 - remove parts "<<endl;
    
    }
    
    
    // get function
    char Car::get_brandname ()const
    {
    	for (int i=0; i<strlen(_brandname); i++)
    	{
    		cout<<*(_brandname+i);
    	}
    	return 0;
    }
    
    int   Car::get_hp (void)const
    {
    	return _hp; 
    }
    
    //print function 
    void Car::print_car()const
    {
    	cout <<"the name is :";
    	cout<<get_brandname ();
    	cout<<"\nwith ";
    	cout<<get_hp ();
    	cout<<" Hp."<<endl ;
    	cout<<"Parts Details :"<<endl;
    	for (int n =0; n<(_nr_parts); n++)
    	{
    		cout << " part Nr <"<<n+1<<"> cost :";
    		cout << *(_parts+n)<<" Euro"<<endl;
    	}
    	
    }
    3rd Main

    Code:
    #include <iostream>
    #include <stdlib.h>
    #include "D_class.h"
    
    
    
    using namespace std;
    
    int main()
    {
    	char *names = NULL;
    	int Hp=0;
    	float *Part=NULL;
    	int Nr_parts=0;
    	int choose=0;
    	char c='n';
    	Car cars[3];
    	
    
    
    	
    
    	for (int i=0; i<3; i++)
    	{
    		
    		cout << "Enter Details for car Nr "<<i+1<<endl;
    		cout << "1- Enter the name : ";
    		names = new char[size];
    		cin.get(names,size);
    		clearBuf();
    
    		cout << "2- Enter the Hp: ";
    		cin >> Hp;
    		cars[i].set_Car(Hp,Part,Nr_parts,names);
                                     if (names)
                                     delete[]names;
                                      names=NULL;
    
    		/*i have stoped here ...... problem with the name;
    		*/
    	
    	
    	}
    
    	return 0;
    }

  9. #9
    carry on JaWiB's Avatar
    Join Date
    Feb 2003
    Location
    Seattle, WA
    Posts
    1,972
    I think your problem is that when the user presses enter after inputting Hp, the '\n' stays in the stream. Adding cin.get(); after cin>>Hp; should fix the problem. That said, I think this is a better way to do what you want:
    Code:
    for (int i=0; i<3; i++)
    {		
    		cout << "Enter Details for car Nr "<<i+1<<endl;
    		cout << "1- Enter the name : ";
    		names = new char[size];
                             //cin.get will not extract the '\n' character
                             //so it is simply easier to use cin.getline
    		cin.getline(names,size);
                             //no need for clearBuf() now 
    		
    
    		cout << "2- Enter the Hp: ";
    		cin >> Hp;
    		cin.get();//removes the '\n' (like clearBuf() did)
    		cars[i].set_Car(Hp,Part,Nr_parts,names);
                                     if (names)
                                     delete[]names;
                                      names=NULL;
    
    
    	
    	}
    Also see my previous post if you want to consider checking the input to make sure it didn't exceed the maximum size
    "Think not but that I know these things; or think
    I know them not: not therefore am I short
    Of knowing what I ought."
    -John Milton, Paradise Regained (1671)

    "Work hard and it might happen."
    -XSquared

  10. #10
    Registered User
    Join Date
    Apr 2005
    Posts
    18
    hey JaWiB
    thank you very much
    you saved alot of my time ..... thank you again
    it works

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. strcmp returning 1...
    By Axel in forum C Programming
    Replies: 12
    Last Post: 09-08-2006, 07:48 PM
  2. getline() don't want to work anymore...
    By mikahell in forum C++ Programming
    Replies: 7
    Last Post: 07-31-2006, 10:50 AM
  3. Why don't the tutorials on this site work on my computer?
    By jsrig88 in forum C++ Programming
    Replies: 3
    Last Post: 05-15-2006, 10:39 PM
  4. fopen();
    By GanglyLamb in forum C Programming
    Replies: 8
    Last Post: 11-03-2002, 12:39 PM
  5. DLL __cdecl doesnt seem to work?
    By Xei in forum C++ Programming
    Replies: 6
    Last Post: 08-21-2002, 04:36 PM