linked list problem

linked list problem

Page 1 of 1

2 Replies - 1365 Views - Last Post: 25 April 2009 - 11:36 PM Rate Topic: -----

#1 siffat  Icon User is offline

  • New D.I.C Head

Reputation: 0
  • View blog
  • Posts: 4
  • Joined: 02-April 09

linked list problem

Posted 25 April 2009 - 01:28 PM

if you run this, enter a valid file and it finds it, then enter an invalid file it checks as it supposed to and prompts user for another file entry...it is here when it checks even with a valid file as outputs the file as valid but does not get out of the loop.




#include <iostream>
#include <fstream>
#include <iomanip>
#include <cstring>
#include <string>

//linked list assignment

using namespace std;

//using enums for phone # types.
//---------------------------------------------------------------------------
enum typephone{w,h,c};

//---------------------------------------------------------------------------
struct record
{
  string ss;
  char firstName;
  string lastName;
  string phoneNumber;
  typephone phoneType;
  string itemRecovered;//have to deal with this cabbie

  record* Next;
	 
};

//linked list first pointer that points to NULL.
record *head = NULL;
//---------------------------------------------------------------------------
//int addRecord(record);
//do not know which one will work
//int addRecord(record);

const int MAX_NUM =500;
const int EXIT = 1;
//
//
int addRecord(record *NewItem, int& count)
{
	//int count = 0;
   if(MAX_NUM > count)
   {
	
	record *data = new record;

	data		  = NewItem;
	data->Next	= head;
	head		  = data;
   	cout<<"The addition is working in addRecord Helper"<<endl;
	count++;
   }
   else
   {
	cout<<"Nothing more can be added: Input has reached MAXIMUM"<<endl;

   }
   return count;
}
//
//
record *retrieve(int& position, int& count)
{
	record *current = head;
	
	for(int i = count - 1; i > position && current != NULL; i--)
	{
		current = current->Next;
	}

	return current;

}
int addEntry(int&);
void deleteit(int&, int&);
void showRecords(bool);
bool isfindssn(int&,int&);
int existingRecords(int);
void match(void);
void writeToFile(char[]);
bool checklast(string);
bool check(string,int,int,int);
bool readFromFile(ifstream&);

void directions();
char firstmenu();
char secondmenu();
//---------------------------------------------------------------------------
int main()
{
  
  int count=0;
  int position = 0;
  //---------------------------------------------------------------------------
//Begin Program
/*
1.	provide user with choices either to enter new entry or use existing ones.\
	->addentry() or exitingRecords()
		->if *head != null;
	{
2.		Menu choices then applies as follows
		--> Show(S) to show all entries
		--> ADD(A) to add new entry
		--> Delete(D) to delete entry by SSN
		--> Match(M) Match entry by SSN from RECOVER>TXT.
		--> Exit(E) Exit the program;save/not save data
	}
	if head != null
	{
	 //do all the cabbie.
	}
	else
	{
		cout<< "The list is Empty, There are no Entries Available";

	}


*/
int reminderCount = 0;
int reminderPosition = 0;
char choice;
directions();
choice = firstmenu();
	do
	{
		 
	   if(choice == 'N')
	   {
				 //new entry, Cabbie
				 reminderCount = addEntry(count);
				 cout<<"delet before submitance---remindercount(addEntry) is " <<reminderCount;
	   }
	   else if(choice == 'E')
	   {
				 
				 reminderCount = existingRecords(count);
				 cout<<"delet before submitance---remindercount(existing) is " <<reminderCount;
	   }
		  
   }while((choice != 'N') || (choice != 'E'));
//
//
}

int addEntry(int& count)  // if the user want to add new residents to the file residents.txt
{
  //linked list 
  record	 *arecord;
  arecord  = new record;
   
  //inhome variable
  bool valid=false;
  char addMore;
  //check before add to list.
  string ssn;
  char first;
  string last;
  string phone;
  char type;
  //begin add function

  do
  {
		do
		{
			cout<<"\nEnter Social Security Number: ";
			cin>>ssn;

			valid=check(ssn,10,3,6);

			if(!valid)
				  cout<<"invalid data, SSN number should in the format XXX-XX-XXXX\n";
		else
			arecord->ss=ssn;

		}while(!valid);

		do
		{
			cout<<"Enter first initial ";  
			cin>>first;

			if(!isalpha(first)) 
				  cout<<"invalid data, First Name starts with Alphabets(A,B,.....Z)\n";
 		else
			arecord->firstName = first;
		}while(!isalpha(first));
	
	 	 first=toupper(first);
	 	 cin.ignore(10, '\n'); //ignore 26 characters or to a newline, whichever comes first
 
	  do
	{
			cout<<"Enter last name ";
			getline(cin,last);   
			valid=checklast(last);   
			if(!valid)
				  cout<<"invalid data\n";
		else
			arecord->lastName = last;
		}while(!valid);

	  do
	{
			cout<<"Enter Phone Number: ";
			cin>>phone;
			valid=check(phone,10,3,7);
			if(!valid)
				  cout<<"invalid data\n";
		else
			arecord->phoneNumber = phone;
		}while(!valid);
	
	  do
	{
		valid=true;
			cout<<"Enter Phone Type\n";
			cout<<"W - work\n";
			cout<<"H - home\n";
			cout<<"C - cell\n";
			cin>>type;
			switch(toupper(type))
			{
				  case 'W':   arecord->phoneType = w;
				 	break;
	 			case 'H':   arecord->phoneType = h;
				 	break;			
	 			case 'C':   arecord->phoneType = c;
				 	break;
	 			default:	valid=false;
				 	cout<<"invalid data, \n";
	 		}
	  }while(!valid);
	//add it to record list max is 500 entries.
		
		count = addRecord(arecord, count);
	//continue untill 'N'
	cout<<"More residents to add(Y/N)?";  // asking for more residents to add.
	cin>>addMore;
	
   }while(toupper(addMore)!='N');
//return the count of records.   
return count;
}
//
//
bool check(string val,int max,int a,int b)
{
  for(int i=0;i < max;i++)
  {
	if(i==a||i==b)
		  {
		if(val[i]!='-')
			 	return false;
		  }
		else
		   	if(!isdigit(val[i]))
				  return false;
  }
  return true;
}   
//
//
bool checklast(string l)
{
 int i;
 if(l.length()>15)
 	return false;
 for(i=0;i<l.length();i++)
 {
	if(!(isalpha(l[i])||l[i]=='\''||l[i]=='-'))
			return false;
	if(i==0)
	   		l[i]=toupper(l[i]);
   	else
		if(isalpha(l[i]))
		 		l[i]=tolower(l[i]);
 }
 return true;
} 
//
void deleteit(int& position, int& count) // if you like to delete an existing resident.
  {
   bool isfound = false;;
   isfound = true;//=findssn(count, position);
   if(isfound)
   {
	//delete it.
		cout<<"my position is "<<position<<endl;
	if(retrieve(position, count) == NULL )
		return;
	else
	{
		int before, after;
		after = position - 1;
		before = position + 1;
		record *current = retrieve(after, count);
		retrieve(before, count)->Next = current;
		count--;
		cout<<"Resident with SSN "<<current->ss<<" deleted\n";
	}
	
   }
   
   return;		
  
  }
//
//
bool isfindssn(int& count, int& position)  // if you like to find an existing resident.
{
 string ssn;
 bool valid;
 record *current;
   showRecords(false);
   do{
	cout<<"\nEnter Social Security Number: ";
	cin>>ssn;
	valid=check(ssn,10,3,6);
	if(!valid)
	  cout<<"invalid data\n";
	}while(!valid);
	position = 0;  
	for(current = head; current != NULL; current = current->Next)
	{
		//returns the position at where the ssn mathed.
		position++;
		cout<<"the potition is isfindssn is " << position<<endl;
		if(current->ss == ssn) 
		{
			
			return true;
		}
		else
		{
			current->Next;
		}
	}

	return false;
	
}
//
//
void match()
{
  cout<<"Match function -- entering "<<endl;
  //variables
  bool isfound = false;
  bool isContinue = false;
  //input variales
  string sn;
  string itemFromFileRecrvd;
  int counter = 0;
  //for RECOVER.TXT FILE
  cout<<"In Match function--entering ";
  //ifstream readFromFile;
 // bool chod = readFromFile(readFromFile);
 //cant get this to work!!! cabbie!!!!!!
  cout<<"Enter the file name you wish to access: ";
  char fileName[50];
  cin>>fileName;
  ifstream readFromFile(fileName,ios::in);
  char yesno;
  do
  {
	if(!readFromFile)
	{
 		cout<<"The file cannot be opened, Do you wish to Continue? ";
   		cin>>yesno;
 		yesno = toupper(yesno);
 		if(yesno =='N')
 		{
				 cout<<"Cannot process your request, back to main Menu"<<endl;
				 isContinue = false;
		}
		else if(yesno == 'Y')
		{
			cout<<"Enter the file name you wish to access: ";
			readFromFile.clear();
			cin>>fileName;
			ifstream readFromFile(fileName,ios::in);
			isContinue = true;
		} 
		else
		{
			cout<<"wrong choice, enter Y(YES) or N(NO) : "<<endl;
			cin>>yesno;
			cout<<"Enter the file name you wish to access: ";
			readFromFile.clear();
			cin>>fileName;
			ifstream readFromFile(fileName,ios::in);			
			yesno = toupper(yesno);
			isContinue = false;
		}
	  }
	else
	{
		//ifstream readFromFile(fileName,ios::in);
		  isContinue = true;
	}
			
  }while((yesno != 'Y') ||(yesno != 'N'));
 
//----------------------------------------------------------------------------------
//----------------------------------------------------------------------------------
if(isContinue)
{
  record *current;
  while (readFromFile.peek()!=EOF)
  {
	
	readFromFile>>sn;//should be the ssn form recover txt file.
	for(current = head; current != NULL; current = current->Next)
	{
		//returns the position at where the ssn mathed.
		//position++;
		//cout<<"the potition is isfindssn is " << position<<endl;
		if (current->ss == sn) 
		{
			readFromFile>>itemFromFileRecrvd;
			if(current->itemRecovered != "NONE")
			{
				//multiple items.
   				itemFromFileRecrvd = "," + itemFromFileRecrvd;
				current->itemRecovered += itemFromFileRecrvd;

			}
 			else
			{	
				current->itemRecovered = itemFromFileRecrvd;
			}
			counter++;
		}
		else
		{
			current->Next;
		}
	}
	if(counter>0)
	{
		showRecords(true);
	}
	else
	{
	cout<<"There are no ssn match found with regards to the items that are recovered";
	}

  }
}
else
{
	cout<<"cannot Continue since no file has been read"<<endl;
}

}

//
//
//
int existingRecords(int count)
{
//-1 so that this can start from 0 in the for loop later, if file found.
  int i=0;
  char type;
  record *recordFile;
  //ifstream fromFile = readFromFile();
  bool isContinue=false;
  bool isdone=false;
  cout<<"Enter the file name you wish to access: ";
  char fileName[50];
  cin>>fileName;
  ifstream readFromFile(fileName,ios::in);
  char yesno;
  do
  {
	if(!readFromFile.is_open())
	{
		 cout<<"File not found" <<endl;
 		cout<<"Enter the file name you wish to access: ";
 		readFromFile.clear();
		//readFromFile.close();
		cin>>fileName;
		ifstream readFromFile(fileName,ios::in);
		//do
		//{
		 if(!readFromFile)
		 {
		   readFromFile.clear();
	   //	readFromFile.close();
		   cout<<"Do you wish to continue?";cabb
		   cin>>yesno;
		   if(yesno == 'N')
		   {
			 exit(0);
		   }
		   else if(yesno == 'Y')
			{
					  cout<<"Enter the file name you wish to access: ";
					  readFromFile.clear();
	 //				 readFromFile.close();
					  cin>>fileName;
					  ifstream readFromFile(fileName,ios::in);
					  isContinue = true;
					  isdone = false;
			}
			else
			{
					
			}
		 }
		 else
		 {  
		 //true
		  isdone =false; 
		  isContinue = true;
		  cout<<"file found"<<endl;
		 }
//		}
   	//	while((isContinue && !isdone) && (!readFromFile));
	}
	  else
	  {
		isContinue = true;
	}
}while(!readFromFile); 			
  

//-----------------------------//file found-----------------------------------------
if(isContinue)
{
 while (readFromFile.peek()!=EOF)
 {
   //i++; 
   //if(i==MAX_RES)	// should not be more than 500 residents.
   //{
	 // cout<<">500 records. extra records to be ignored\n"; // error message
	  //i--;//do not understand deleting here.
	  //return i;
   //}
   //initialize a record pointer here.
   recordFile = new record;
   //no check needed since all info are from file.
   readFromFile>>recordFile->ss;
   readFromFile>>recordFile->firstName;
   readFromFile>>recordFile->lastName;
   readFromFile>>recordFile->phoneNumber;
   readFromFile>>type;
   //type = recordFile->phoneType;
   switch(toupper(type))
	{
		case 'W':   recordFile->phoneType=w;
				 break;
		case 'H':   recordFile->phoneType=h;
				 break;			
		case 'C':   recordFile->phoneType=c;
				 break;
	 }
   }
   
   i = addRecord(recordFile, count);  
   count += i;
   readFromFile.close();
}
else
{
	cout<<"cannot process this procedure to obtain exiting resident info"<<endl;
	
}
cout<<"in existingRecords---adding file to linked list";

return count;
} 
//
//
int exit()
{
   
   char ans2,ans;
   char fileName[50];
   cout<<"Do you want to save data? ";
   cin>>ans;
   ans = toupper(ans);
  do
  {
   if(ans == 'Y')
   {
	cout<<"Enter the file name you wish to save data in: ";
	cin>>fileName;
		  do
	 	{
			  
		fstream outToFile(fileName,ios::out);
 		if(!outToFile)
		{

 		 writeToFile(fileName);
		 return EXIT;
 		 
		}
		else
		{
				 
			  cout<<"Are you sure you want to Over Write file " << fileName<<"?";
	 	 
		 	cin>>ans2;
			ans2 = toupper(ans2);
			do
			{
				  
				if (ans2 == 'Y')
				{
					cout<<"Right choice for ans2 ";
					cout<<"You have chosen to over write current file "<< fileName;
					writeToFile(fileName);
					return EXIT;

				}
				else if (ans2 == 'N')
				{
				   	cout<<"Enter the file name you wish to Save file in:";
					outToFile.clear();
					cin>>fileName;
				}
				else 
				  {
					cout<<"wrong choice, enter Y(YES) or N(NO) : "<<endl;	
					cout<<"Re enter your coice (either Y or N) ";
					cin>>ans2;
				  }
			   }while((ans2 != 'Y') ||(ans2 != 'N'));
		}

	 	}while((ans2 != 'Y') ||(ans2 != 'N'));
  }
  else if (ans == 'N')
  {
	cout<<"nothing to do but leave.";
	return EXIT;
  }
  else
  {
	cout<<"wrong choice, enter Y(YES) or N(NO) : "<<endl;
	cin>>ans;
  }
}while((ans != 'Y') ||(ans != 'N'));
  
 return EXIT;
}
//
//
void writeToFile(char fileName[50])
{
 fstream outFile(fileName, ios::out);
 do
 {
  cout<<"in writeToFile -- enters function";
 // fstream outFile(fileName, ios::out);
  if(outFile)
  {
	cout<<"writeToFile function--writing to file"<<endl;
	record *current;
	for(current = head; current != NULL; current = current->Next)
	  {
		outFile<<current->ss<<""<<current->firstName<<""<<current->lastName<<"";
		outFile<<current->phoneNumber<<""<<current->phoneType;			
		outFile<<endl;	  
	}
				  
	outFile.close();
   }
   else
   {
	//should never come here.
	cout<<"There is a problem saving data, please contact cabbie";
	outFile.clear();

   }
  }while(!outFile);

}

//
void showRecords(bool isItemRecovered)   // showing the data file residents.txt
{
  record *current;
  if(isItemRecovered)
  {
	 cout<<"	  Name		  Phone		   Number	   Item Recovered\n";
	 cout<<" -------------  -------------  -----------	   --------------- \n";
	 for(current = head; current != NULL; current = current->Next)
	 {
		 if(current->itemRecovered != "NONE")
		 {
	 		cout<<current->firstName<<" "<<setw(15)<<left<<current->lastName<<" "<<current->phoneNumber;
	 		cout<<"  "<<current->itemRecovered<<"  ";
	   		cout<<endl;
		 }
	 }
  }
  else
  {
	cout<<"	  Name		  SSN		   Phone	   Type\n";
	cout<<" -------------  -------------  -----------	----- \n";
	//pointer declaration
	
	for(current = head; current != NULL; current = current->Next)
	{
		cout<<current->firstName<<" "<<setw(15)<<left<<current->lastName<<" "<<current->ss;
		cout<<"  "<<current->phoneNumber<<"  ";
	   		if(current->phoneType==w) 
		{		
				  cout<<"work";
		}
	   		else if(current->phoneType==h) 
		{
			cout<<"home";

		}
		else
		{
			cout<<"cell";
		}
			  
			cout<<endl;
	}
 }
  return;
}
//
//
void directions()
{
	cout<<"The local police department keeps a file of data on city residents who have marked their belongings with their Social Security Numbers (SSNs)\n";
	return;
}
//
//first menu option 
char firstmenu()
{
	char answer;
 	cout<<"Which data would you like to use?\n";  // asking for new residents or existing residents
	cout<<"  N - New resident data\n";
 	cout<<"  E - Existing resident data\n";
 	cout<<"<------------------------------>"<<endl;
 	cout<<" Enter choice either to add Resident OR View our listing: ";
 do
   {
	cin>>answer;
		answer=toupper(answer);
		if(answer!='E'&&answer!='N')
	   		cout<<"invalid choice: re-enter\n";
   }
   while(answer!='E'&&answer!='N');

  return answer;
}
//
//
char secondmenu()
{
 char answer;
 cout<<"\n\nWhat would you like to do?\n"; // after choosing the "E" for existing resident.
 cout<<"  A - Add a resident\n";
 cout<<"  S - Show the existing residents\n";
 cout<<"  F - Find a resident\n";
 cout<<"  D - Delete a resident\n";
 cout<<"  E - Exit\n";
 
 do
   {
	cin>>answer;
		answer=toupper(answer);
		if(answer!='A'&&answer!='S'&&answer!='F'&&answer!='D'&&answer!='E')
	   		cout<<"invalid choice: re-enter\n";
	}while(answer!='A'&&answer!='S'&&answer!='F'&&answer!='D'&&answer!='E');
  return answer;
}


//
//
/*bool readFromFile(ifstream readFile)
{
		 
  cout<<"Enter the file name you wish to access: ";
  char fileName[50];
  cin>>fileName;
  readFile(fileName,ios::in);
  char yesno;
  do
  {
	
	if(!readFromFile)
	{
 		cout<<"The file cannot be opened, Do you wish to Continue? ";
	   		cin>>yesno;
 		yesno = toupper(yesno);
	   	}
		else
	{
		cout<<"The File "<<fileName<<" is found, do you wish to proceed?";
		cin>>yesno;
 		yesno = toupper(yesno);
	}
	//check yesno options	
		
	if (yesno == 'Y')
	{
		cout<<"Enter the file name you wish to access: ";
		readFromFile.clear();
		cin>>fileName;
		ifstream readFromFile(fileName,ios::in);
	}
	else if(yesno =='N')
	{
 		readFromFile.clear();
 		return false;
	}
	else
	{
		cout<<"wrong choice, enter Y(YES) or N(NO) : "<<endl;
		readFromFile.clear();	
		cin>>yesno;
		yesno = toupper(yesno);
	}
	 	
  
  }while((yesno != 'Y') ||(yesno != 'N'));	
  
return true;
}

*/


Attached File(s)



Is This A Good Question/Topic? 0
  • +

Replies To: linked list problem

#2 Martyr2  Icon User is offline

  • Programming Theoretician
  • member icon

Reputation: 4332
  • View blog
  • Posts: 12,127
  • Joined: 18-April 07

Re: linked list problem

Posted 25 April 2009 - 09:40 PM

In this code segment below, where will choice ever change once they have chosen?

    do
    {
         
       if(choice == 'N')
       {
                 //new entry, Cabbie
                 reminderCount = addEntry(count);
                 cout<<"delet before submitance---remindercount(addEntry) is " <<reminderCount;
       }
       else if(choice == 'E')
       {
                 
                 reminderCount = existingRecords(count);
                 cout<<"delet before submitance---remindercount(existing) is " <<reminderCount;
       }
         
   }while((choice != 'N') || (choice != 'E'));



Notice that no where in the loop will choice ever be set to a new value. So if I choose N or E the first time and run through adding the entry, it will reach the while statement and repeat the loop with choice being the same value as before.

You have to reprompt for a new value for "choice" each time through the while loop. Otherwise it will never change and be stuck in the loop forever.

:)
Was This Post Helpful? 0
  • +
  • -

#3 r.stiltskin  Icon User is offline

  • D.I.C Lover
  • member icon

Reputation: 1833
  • View blog
  • Posts: 4,927
  • Joined: 27-December 05

Re: linked list problem

Posted 25 April 2009 - 11:36 PM

View Postsiffat, on 25 Apr, 2009 - 03:28 PM, said:

if you run this, enter a valid file and it finds it, then enter an invalid file it checks as it supposed to and prompts user for another file entry...it is here when it checks even with a valid file as outputs the file as valid but does not get out of the loop.


First of all, your code is very difficult to read because of your placement of all of the brackets at the left-hand margin. Parentheses should be indented to the same level as the statement they relate to.
For example:
int main()
{
	if( x > y )
	{
		some code
		some more code 
		while( z )
		{
			still more
			and more
		}
	}
}


I assume you are referring to your existingRecords() function.

The problem is that this block of code:
  ifstream readFromFile(fileName,ios::in);
  char yesno;
  do
{
	if(!readFromFile.is_open())
{
		 cout<<"File not found" <<endl;
		 cout<<"Enter the file name you wish to access: ";
		 readFromFile.clear();
		//readFromFile.close();
		cin>>fileName;
		ifstream readFromFile(fileName,ios::in);
		//do
		//{
		 if(!readFromFile)
{
		   readFromFile.clear();
	   //	readFromFile.close();
		   cout<<"Do you wish to continue?";cabb
		   cin>>yesno;
		   if(yesno == 'N')
{
			 exit(0);
}
		   else if(yesno == 'Y')
{
					  cout<<"Enter the file name you wish to access: ";
					  readFromFile.clear();
	 //				 readFromFile.close();
					  cin>>fileName;
					  ifstream readFromFile(fileName,ios::in);
					  isContinue = true;
					  isdone = false;
}
			else
{
				   
}
}
		 else
{  
		 //true
		  isdone =false;
		  isContinue = true;
		  cout<<"file found"<<endl;
}
//		}
	   //	while((isContinue && !isdone) && (!readFromFile));
}
	  else
{
		isContinue = true;
}
}while(!readFromFile);			

is hopelessly tangled. You have 3 separate definitions of ifstream readFromFile, two of which are local to if blocks (one embedded inside the other). When those blocks go out of scope, those local ifstream objects no longer exist. Aside from that the logic is confused and confusing. Also, testing with if( !readFromFile ) and readFromFile.clear() are not your best choices in this context.

Here are some suggestions:
at the beginning of the function existingRecords()
- don't prompt for the filename
- define ifstream readFromFile but do not try to open it
- define isContinue and initialize it to true
- isdone is unnecessary; delete it
- your other variables seem ok as you have them

Now you can do all the prompting, keyboard input, and file opening in a while loop:
while( !readFromFile.is_open() && isContinue ) {
// prompt for filename, read it in, and try to open it
//...
// if( !readFromFile.is_open() )
// ask if user wants to try again
// validate user's y/n response (perhaps using an embedded while loop to
//   require that user inputs a 'Y' or 'y' or 'N' or 'n')
// and set isContinue to true or false accordingly
}

Was This Post Helpful? 1
  • +
  • -

Page 1 of 1