Link-listed addressbook

Reply

Join Date: Feb 2007
Posts: 40
Reputation: Shaabangbang is an unknown quantity at this point 
Solved Threads: 0
Shaabangbang Shaabangbang is offline Offline
Light Poster

Link-listed addressbook

 
0
  #1
Apr 2nd, 2007
hey guys, uhh ok remember the old addressbook problem? well i solved it :cheesy: ! but now my prof gave us the same assignment but we have to do it as linked lists.. and i dont know how to use linked lists quite well yet.. this is my original code without the linked lists.

  1. /*includes*/
  2.  
  3. #include <stdio.h>
  4. #include <string.h>
  5. #include <ctype.h>
  6.  
  7. //Structure containing all contact information fields
  8. struct contact {
  9. char firstname [40]; //first name field
  10. char lastname [40]; //last name field
  11. char address [100]; //address field
  12. char postalcode [7]; //postal code field
  13. char phone[11]; //phone number field
  14. struct contact *nextPtr; //pointer to next contact
  15. };
  16.  
  17. struct student *pFirst = NULL;
  18. struct student *pLast = NULL;
  19.  
  20. /*Function Prototypes*/
  21. int enterchoice (void);
  22. int addnewcontact ();
  23. int isvalidpostalcode (struct contact pPtr[]);
  24. int isvalidphone (struct contact nPtr[]);
  25. void flush_in ();
  26. int filewrite ();
  27. int displaydata ();
  28. int loaddata ();
  29. int finalsave ();
  30. void formatphonenumber (struct contact *gPtr);
  31. void formatpostalcode (struct contact *hPtr);
  32. void wordcap (struct contact aPtr[]);
  33. void search();
  34. void ClearList(struct student *pF);
  35.  
  36. /*i defined globally as a counter*/
  37. int i=1;
  38.  
  39. /* Main Module
  40. Takes no input
  41. goes to the enter choice menu
  42. */
  43. int main (void){
  44.  
  45. int choice;
  46.  
  47. printf ("\n *** Personal Contact Book v1.0 *** \n");
  48.  
  49. enterchoice (); //go to the main menu
  50.  
  51. return 0; //return 0 indicating successful termination
  52. }
  53.  
  54. //Choice Entering Module
  55. //Takes integer as input
  56. //according to users choice, it goes to 6 different modules
  57. int enterchoice (void)
  58. {
  59. int choice;
  60.  
  61.  
  62. printf ("1)Add New Contact.\n2)Display Current Contacts.\n3)Search for a contact.\n4)Save Contacts to File.\n5)Load Contacts from File.\n6)Exit.\n");
  63. printf (">");
  64. scanf ("%d", &choice);
  65.  
  66. switch (choice){ //starting switch case
  67. case 1:
  68. addnewcontact(); //go to the adding a new contact module to add a new contact
  69. break;
  70. case 2:
  71. displaydata (); //go to the display contact module to display latest contact added
  72. break;
  73. case 3:
  74. search(); //go to the contact search module to search for a saved contact
  75. break;
  76. case 4:
  77. filewrite(); // go to the file saving module to save contacts inputted
  78. break;
  79. case 5:
  80. loaddata(); //go to the loading module to load and print saved contacts
  81. break;
  82. case 6: finalsave();//go to the final save module to save whatever changes were made to the file
  83. break;
  84. default: printf ("\nInvalid choice\n");
  85. enterchoice(); //if choice was invalid, inform user then re-display menu
  86. break;
  87. }
  88.  
  89. }
  90.  
  91. /*add new contact module
  92. takes first name, last name,
  93. address, postal code and phone
  94. number as input, after reading is done,
  95. goes back to main menu*/
  96.  
  97. int addnewcontact ()
  98. {
  99.  
  100. struct contact * pNew = NULL;
  101.  
  102. char choice = 'y'; //defining local variables
  103. int z, y;
  104.  
  105. pNew = (struct contact *) (malloc( sizeof( struct contact)));
  106.  
  107.  
  108. FILE *outfile; //declaring file pointer
  109.  
  110. outfile = fopen ("contactlist.dat", "w"); //opening file
  111.  
  112. while (choice == 'y'){ //start of outer while loop
  113. printf ("\nAdding new contact: \n");
  114. printf ("First name: ");
  115. scanf("%s",pNew->firstname); //reading first name
  116. printf ("Last name: ");
  117. scanf("%s",pNew->lastname); //reading last name
  118. printf ("Address: ");
  119. flush_in();
  120. gets (pNew->address); //reading address
  121. printf ("Postal code: ");
  122. scanf("%s",pNew->postalcode); //reading postal code
  123.  
  124. z = isvalidpostalcode (pNew->postalcode); //going to isvalidpostalcode module to validate postal code
  125.  
  126. //start of inner while loop, checking if inputted postal code is correct (module would return 1 in that case)
  127.  
  128. while (z != 1){
  129. printf ("Invalid postal code, please enter a correct one.\n");
  130. printf ("Postal code: ");
  131. scanf("%s",pNew->postalcode);
  132. flush_in();
  133. z = isvalidpostalcode (pNew->postalcode); //validate newly entered postal code
  134. }
  135. printf ("Phone number: ");
  136. scanf("%s",pNew->phone); //reading phone number
  137. flush_in();
  138.  
  139. y = isvalidphone (pNew->phone); //going to isvalidphone module to validate phone number
  140.  
  141. //start of third inner while loop, checking if inputted phone number is correct (module would return 1 in that case)
  142.  
  143. while (y != 1){
  144. printf ("Invalid phone number, Please enter a 10-Digit phone number starting with the area code.\n");
  145. printf ("Phone number: ");
  146. scanf("%s",pNew->phone); //reading new phone number
  147. flush_in();
  148. y = isvalidphone (pNew->phone); //validate newly entered phone number
  149. }
  150.  
  151.  
  152. printf ("\nWould you like to enter a new contact? "); //see if user wants to enter another contact
  153. scanf ("%c", &choice);
  154. i++;//increment records counter
  155.  
  156. pNew->nextPtr = NULL;
  157.  
  158. if (pFirst == NULL)
  159. pFirst = pNew;
  160.  
  161. if (pLast != NULL)
  162. pLast->nextPtr = pNew;
  163.  
  164. pLast = pNew;
  165. }
  166.  
  167. ClearList (pFirst);
  168.  
  169. enterchoice (); //go back to main menu
  170. return 0; //return 0 to indicate successful termination
  171. }
  172.  
  173. /*This module takes the inputted
  174. postal code in the addnewcontact module
  175. and validates it, returns 1 if
  176. correct, or returns 0if incorrect*/
  177.  
  178. int isvalidpostalcode(struct contact pPtr[])
  179. {
  180. int length = (int)(strlen(pPtr)); //finding the length of the passed string
  181.  
  182. if (length == 6){ //if the length is 6 characters, check if the sequence is 'letter' 'number' 'letter' 'number' 'letter' 'number'
  183. if (isalpha(pPtr[0]) && isdigit(pPtr[1]) && isalpha(pPtr[2]) && isdigit(pPtr[3]) && isalpha(pPtr[4]) && isdigit(pPtr[5]))
  184. {
  185. return 1; //return 1 is this is true
  186. }
  187. else{
  188. return 0; //otherwise return 0
  189. } //end of inner else statement
  190. }
  191. else {
  192. return 0; //otherwise if the length exceeds or is less than 6 return 0
  193. } //end of outer else statement
  194. }
  195.  
  196. /*Validating phone number function,
  197. takes passed phone number as input
  198. returns 1 if its valid, and 0 if invalid*/
  199.  
  200. int isvalidphone (struct contact nPtr[])
  201. {
  202. int length = (int)(strlen(nPtr)); //finding length of string
  203.  
  204. if (length <= 10){ //if the length is less than or equal to 10 then check if sequence is 10 numbers
  205. if (isdigit(nPtr[0]) && isdigit(nPtr[1]) && isdigit(nPtr[2]) && isdigit(nPtr[3]) && isdigit(nPtr[4]) && isdigit(nPtr[5]) && isdigit(nPtr[6]) && isdigit(nPtr[7]) && isdigit(nPtr[8]) && isdigit(nPtr[9]))
  206. {
  207. return 1; //return 1 if this is true
  208. }
  209. else{
  210. return 0; //otherwise if its false return 0
  211. }//end of inner else statement
  212. }
  213. else {
  214. return 0; //otherwise if length exceeds 10 digits, then return 0
  215. } //end of outer else statement
  216. }
  217.  
  218. /*flush function, takes no input
  219. and has no output*/
  220.  
  221. void flush_in (){
  222. int ch; //defining local variables
  223. while ((ch = fgetc (stdin))!= EOF && ch != '\n'){}
  224. }
  225.  
  226. /*Contact information saving function
  227. takes all contact information inputted in the
  228. addnewcontact module, and prints them to the file*/
  229.  
  230. int filewrite (){
  231. int u; //defining local variables,
  232. struct student *pF;
  233.  
  234. struct student *pC=pF;
  235. FILE *xPtr; //defining file pointer
  236.  
  237. xPtr = fopen ("contactlist.dat", "w"); //opening file for writing
  238.  
  239. for (u=1;u<i;u++){ //going through the entire file
  240. fprintf (xPtr,"%s\n", pC->firstname); //writing first name
  241. fprintf (xPtr,"%s\n", pC->lastname); //writing last name
  242. fprintf (xPtr,"%s\n", pC->address); //writing address
  243. fprintf (xPtr,"%s\n", pC->postalcode); //writing postal code
  244. fprintf (xPtr,"%s", pC->phone); //writing phone number
  245. }
  246.  
  247. fclose (xPtr);//closing file
  248.  
  249. printf ("\nContact information saved successfully!\n"); //informing user that the process was a success
  250. printf ("\n");
  251. enterchoice (); //going back to the main menu
  252. return 0;
  253. }
  254.  
  255. /*Data display function,
  256. outputs the last contact information
  257. entered, takes input from addnewcontact module*/
  258.  
  259. int displaydata (struct student *pF){
  260. //defining local variables
  261. int j;
  262. j=i-1;
  263.  
  264. struct student *pC = pF;
  265.  
  266. printf ("\n");
  267. printf ("First name: ");
  268. wordcap (pC->firstname); //capitalizing then printing last first name entered
  269. printf ("Last name: ");
  270. wordcap (pC->lastname); //capitalizing then printing last last name entered
  271. printf ("Address: %s\n", pC->address); //printing last address entered
  272. printf ("Postal code: ");
  273. formatpostalcode (pC->postalcode); //formatting then printing last postal code entered
  274. printf ("Phone number: ");
  275. formatphonenumber (pC->phone); //formatting then printing last postal code entered
  276.  
  277. printf ("\n");
  278. enterchoice(); // going back to main menu
  279. }
  280.  
  281. /*Loading function, takes input saved into the file
  282. from the filewrite function and reads it from the file
  283. then prints it to the user*/
  284.  
  285. int loaddata (){
  286. //declaring local variables
  287. int u=1;
  288.  
  289. FILE *cPtr; //defining file pointer
  290.  
  291. cPtr = fopen ("contactlist.dat", "r"); //opening file for reading
  292.  
  293. if (cPtr == '\0'){ //if file is empty, then inform user
  294. printf ("Error, File is empty\n");
  295. }
  296.  
  297. else{ //otherwise read from file and print
  298.  
  299. //while the end of the file is not reached, and the maximum number of records has not been reached either, print the information
  300.  
  301. while (!feof(cPtr) && u < i)
  302. {
  303. fgets (contact[u].firstname, 40, cPtr); //read the first name
  304. wordcap (contact[u].firstname); //captitalize it then print it
  305. fgets (contact[u].lastname, 40, cPtr); //read last name
  306. wordcap (contact[u].lastname); //capitalize it then print it
  307. fgets (contact[u].address, 100, cPtr); //read address
  308. printf ("%s\n", contact[u].address); //print address
  309. fgets(contact[u].postalcode, 7, cPtr); //read postal code
  310. formatpostalcode (contact[u].postalcode); //format it then print it
  311. fgets (contact[u].phone, 10, cPtr); //read phone number
  312. formatphonenumber (contact[u].phone); //BUG: prints first contacts phone number incorrectly, then prints correctly for other contacts
  313. printf ("\n");
  314. u++;
  315. cPtr++;
  316. }
  317.  
  318.  
  319.  
  320. fclose (cPtr);
  321. }
  322. enterchoice ();
  323. }
  324.  
  325. /*Final save function,
  326. prompts user if he/she wants
  327. to save any unsaved changes in his/her
  328. contact information, takes choice as input,
  329. writes unsaved information to file*/
  330.  
  331. int finalsave ()
  332. {
  333.  
  334. //declaring local variables
  335. char choice; //declaring choice variable
  336. int u; //declaring counter
  337.  
  338. FILE *outfile; //declaring file pointer
  339.  
  340. printf ("Would you like to save your contacts before leaving? "); //prompting user if he/she wants to save unsaved changes
  341.  
  342. scanf ("%s", &choice); //reading users response
  343.  
  344. if (choice == 'y') //if user responds y as in yes, then open the file, and save all contact information
  345. {
  346. outfile = fopen ("contactlist.dat", "w"); //opening file
  347. for (u=1;u<i;u++){ //going through all contents of file
  348. fprintf (outfile,"%s\n", contact[u].firstname); //writing first name
  349. fprintf (outfile,"%s\n", contact[u].lastname); //writing last name
  350. fprintf (outfile,"%s\n", contact[u].address); //writing address
  351. fprintf (outfile,"%s\n", contact[u].postalcode); //writing postal code
  352. fprintf (outfile,"%s\n", contact[u].phone); //writing phone number
  353. } //end of for loop
  354. fclose (outfile); //closing file
  355. printf ("\nContact information saved successfully!\n"); //inform user operation was successful
  356. printf ("\n");
  357. }
  358. printf ("Bye!\n");
  359. return 0; //return 0 indicating successful termination
  360. }
  361.  
  362. /*Formatting phone number module
  363. Takes passed phone number, and puts area code
  364. in brackets, then puts a space, and a hyphen character
  365. 3 numbers after that*/
  366.  
  367. void formatphonenumber (char *gPtr){
  368. //declaring counters
  369. int k, j, l;
  370.  
  371. putchar ('('); //inputting opening bracket before first 3 numbers
  372.  
  373. for (k = 0; k < 3; k++){ //going through first 3 numbers
  374. putchar(gPtr[k]); //print them
  375. } //end of for loop
  376.  
  377. putchar (')'); //input a closing bracket after 3 numbers have been printed
  378. putchar (' '); //input a space after the closing bracket has been printed
  379.  
  380. for (j = 3; j < 6; j++){ //going through 3 more numbers, printing as we go
  381. putchar(gPtr[j]);
  382. }
  383. putchar ('-'); //after 3 more numbers have been printed, input a hyphen
  384.  
  385. for (l = 6; l < 10; l++){ //go through the last 4 numbers, print as we go
  386. putchar(gPtr[l]);
  387. }
  388. printf ("\n");
  389. }
  390.  
  391.  
  392. /*formatting postal code,
  393. works almost same way as the
  394. formatphonenumber function;
  395. takes passed postal code,
  396. capitalizes the letters and inputs a
  397. hyphen after 3 characters have
  398. been printed*/
  399.  
  400. void formatpostalcode (char *hPtr){
  401. //declaring local variables
  402. int f, g; //declaring counters
  403. char c, k, d;
  404.  
  405. for (f = 0; f <3; f++){ //going through first 3 characters, converting to uppercase and printing as we go
  406. c = toupper (hPtr[f]);
  407. putchar (c);
  408. } //end of for loop
  409.  
  410. putchar ('-'); //input hyphen after 3 characters have been printed
  411.  
  412. for (g = 3; g < 6; g++){ //go through last 3 letters, converting to uppercase and printing as we go
  413. c = toupper (hPtr[g]);
  414. putchar (c);
  415. } //end of for loop
  416. printf ("\n");
  417. }
  418.  
  419. /*Search function, takes
  420. last name as input, and ouputs
  421. the record with a last name
  422. that matches the inputted last name*/
  423.  
  424. void search (){
  425.  
  426. //declaring local variables
  427. char lname[40]; //declaring last name variable
  428. int u, choice; //counter and choice variables, respectively
  429.  
  430. printf ("Please enter contacts last name: "); //prompting user to input last name
  431. scanf ("%s", lname);
  432.  
  433. FILE *outfile; //declaring file pointer
  434.  
  435. outfile = fopen ("contactlist.dat", "rt"); //opening file
  436.  
  437. for (u=0; u<=i;u++){ //going through contents of file
  438.  
  439. if (strcmp (lname, contact[u].lastname)== 0){ //if last name is found, then print all information that accompanies it
  440. printf ("\nFirst Name: ");
  441. wordcap (contact[u].firstname);
  442. printf ("Last Name: ");
  443. wordcap(contact[u].lastname);
  444. printf ("Address: %s\n", contact[u].address);
  445. printf ("Postal Code: ");
  446. formatpostalcode (contact[u].postalcode);
  447. printf ("Phone Number: ");
  448. formatphonenumber (contact[u].phone);
  449.  
  450. }
  451. fclose (outfile); //closing file
  452. }
  453. printf ("\n");
  454. enterchoice(); //back to main menu
  455. }
  456.  
  457. /*wordcap function, words similarily to
  458. formatphonenumber and formatpostalcode,
  459. takes passed word as input, and outputs
  460. its first letter capitalized*/
  461.  
  462. void wordcap (char aPtr[]){
  463.  
  464. //declaring local variables
  465. int k, l; //declaring counters
  466. char c;
  467. char d;
  468. int length = ((int) strlen(aPtr)); //finding length of passed word
  469.  
  470. for (k = 0; k < 1; k++){ //going to beginning of the string and capitalizing first character
  471. c = toupper (aPtr[k]);
  472. putchar (c); //printing capitalized character
  473. }
  474. for (l = 1; l < length;l++){ //going through rest of string and changing everything to lower case along with it
  475. d = tolower (aPtr[l]);
  476. putchar(d);
  477. }
  478. printf ("\n");
  479. }

Thanks for all the help u guys gave me so far by the way,

like i understand the concept of a linked list but i dont get how to implement it in my code to replace things like contact[u].firstname and contact[u].lastname..

thanks in advance
Last edited by Shaabangbang; Apr 2nd, 2007 at 4:44 pm.
Reply With Quote Quick reply to this message  
Join Date: Oct 2005
Posts: 318
Reputation: Clinton Portis is an unknown quantity at this point 
Solved Threads: 32
Clinton Portis's Avatar
Clinton Portis Clinton Portis is offline Offline
Posting Whiz

Re: Link-listed addressbook

 
0
  #2
Apr 2nd, 2007
edit: This is in c++, so replace 'new' with 'malloc()', 'delete' with 'free', and cout/cin with printf()/fgets()


instead of creating an array of structs like contact[u],

1. create a pointer of type 'contact'

2. everytime you need a new 'contact' node, create it by calling contact *cntcPtr = new contact;

3. After you create your new 'contact' nodes, be sure the last node you've created (if any) has a pointer in it, that points to the newly created node. sounds complicated, but it's really quite simple, and would probably look something like this:
  1. PrevNode->next = cntctPtr;

4. You can populate your new node just by setting each attribute individually.
  1. cout << "Enter Name: ";
  2. cin >> cntctPtr->name;
  3. etc..
  4. ...

5. Be sure that for your singly-linked list, that you always keep a dedicated pointer to the head node. If no head node, headptr = NULL;

6. For a singly linked list, it's probably a good idea to also have a dedicated pointer to the most newly created node.. 'PrevNode'

7. Also, make sure that if using tail-node insertion, that all newly created nodes 'next' pointer are initialized to NULL. If using head-node insertion, make sure that the first node you create, the 'next' pointer is initialized to NULL.

8. Here is a basic outline on how to traverse your singly-linked list if you wanted to look for specific items:
  1. //Start at the front of the list and work to the back
  2. contact *temp = headptr;
  3.  
  4. while(strcmp(temp->name, target_name) != 0 && temp != NULL)
  5. {
  6. temp = temp->next;
  7. }
  8.  
  9. //At this point, as long as temp does not equal NULL, 'temp' should be the node ye' are looking for.

9. be sure you delete your linked list when the user is done, or when the program terminates.
  1. contact *temp = headptr;
  2.  
  3. while(headptr != NULL)
  4. {
  5. headptr = temp->next;
  6. delete temp;
  7. }

That's probably enough to get ye' started on your singly-linked list. Once you got the basics down, it's really not as hard as you think Just keep in mind that pointers are data types just like any other.. int's hold integer values.. floats hold floating point decimals.. char's hold ascii table values.. and pointers hold memory addresses. Piece of cake
Last edited by Clinton Portis; Apr 2nd, 2007 at 6:36 pm.
Reply With Quote Quick reply to this message  
Reply

This thread is more than three months old.
Perhaps start a new thread instead?
Message:



Similar Threads
Other Threads in the C Forum
Thread Tools Search this Thread



About Us | Contact Us | Advertise | DaniWeb | Acceptable Use Policy | RSS Feed

©2003 - 2009 DaniWeb® LLC