Hi guys, i have to create a program that would store a persons full name, phone number, address, and postal code into a file named contactlist.dat, so far no problems, but im also supposed to use char for every single one, even the phone number, does anyone know how to do that? this is what i got so far for the code

#include <stdio.h>

struct contact {
	char firstname [40];
	char lastname [40];
	char address [100];
	char postalcode [6];
	char phone[10];
};

int enterchoice (void);
int isvalidphone (void);
int isvalidpostal (void);
int isvalidaddress (void);

int main (void){

FILE *cfPtr;
int choice;
struct contact data = {"", "", "", "", ""};

if ((cfPtr = fopen ("contactlist.dat", "rb+")) == NULL){
	printf ("File could not be opened.\n");
	}
        else{
	while ((choice = enterchoice() != 6)) {
	  printf ("First name: ");
	  fscanf ("%s", data.firstname);
	  printf ("Last name: ");
	  fscanf ("%s", data.lastname);
	  printf ("Address: ");
	  fscanf ("%s", data.address);
	  printf ("Postal code: ");
	  fscanf ("%s", data.postalcode);
	  printf ("Phone number: ");
	  fscanf ("%s", data.phone);
	
	fwrite (&data, sizeof (struct contact), 1, cfPtr);
	printf ("Would you like to enter a new contact? (1/0)");
	scanf ("%d", choice);
	}
    fclose (cfPtr);
    }
  return 0;

anyone know how to input a number as a character array???? or an alternative to that??
Any help is greatly appriciated!

Member Avatar for iamthwee

Are you not already using char for every one?

yeah, i am, but i dont get how to scan it when its supposed to be a number, or an address which has a house number, or a canadian postal code.. e.g. N8X 4H4.. its like, a char, a number, a char, a number, a char, and a number, its hard to do it when you're using a char array, for me it is atleast..

Member Avatar for iamthwee

well do you have to do any maths with it like
2 + 2 = 5 ? If not then leave it as a char.

well no.. just have to input it and save it.. but the problem is i cant just say scanf ("%s", data.phone);

This is what happens when i have a space in my address

*** Personal Contact Book v1.0 ***
1) Add New Contact.
2)Display Current Contacts.
3)Search for a contact.
4)Save Contacts to File.
5)Load Contacts from File.
6)Exit.
>1
First name: john
Last name: smith
Address: 3654 park street
Postal code: Phone number: Would you like to enter a new contact? (1/0)1
Segmentation fault
shaabangbang@shaabangbang:~$

it just skips the postal code and phone number, and this is what happens when i have no spaces in my address, or postal code

First name: john
Last name: smith
Address: 3654parkstreet
Postal code: N8H4K4
Phone number: 5199916678
Segmentation fault
shaabangbang@shaabangbang:~$

i keep getting a segmentation fault no matter what..:sad:

Member Avatar for iamthwee

Well that's a problem with scanf not integers or chars?

If you want scanf() to read input not stopping when encounters a space, you have to tell it how:

scanf("%[^\n]", array).

That will read input until encounters a "new line". After that get riddle of the new line with a getchar().

However try to learn other ways of reading input.

Stop using fscanf() and use fgets() instead. fscanf() is not good (nor safe) the way you are using it. Especially with postal codes. Since you are using the data as a string, you didn't leave room for the ending '\0'

Also, read this about scanf() , which applies to fscanf() too.

oh, ok, thanks alot, i fixed it, but does anyone know how to validate a postalcode or a phone number? like for example, for a phone number it has to be (areacode) (prefix) (suffix), where the area code, prefix and suffix are 3 numbers, 3 numbers, and 4 numbers, respectively.

and the area code its like, N9F 5H5.. like char number char number char number, i dont know how to write a function to validate those, any help is appriciated! thanks a bunch for the help so far!

Member Avatar for iamthwee

simple write your own function to do it.

Just test each character in each position to see if it is of the proper type. Look up the is[I]xxx[/I]() functions, like isdigit() and isalpha()

i did.. this is it:

#include <stdio.h>
#include <string.h>
#include <ctype.h>

struct contact {
        char firstname [40];
        char lastname [40];
        char address [100];
        char postalcode [7];
        char phone[10];
};

int enterchoice (void);
int addnewcontact (FILE *fPtr);
int isvalidpostalcode (char pPtr[]);
int main (void){
int choice;
  printf ("*** Personal Contact Book v1.0 ***\n");
  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");
  printf (">");
scanf ("%d", &choice);

FILE *cfPtr;
if ((cfPtr = fopen ("contactlist.dat", "rb+")) == NULL){
        printf ("File could not be opened.\n");
        }
else{
        while (choice != 6){
          switch (choice){
                case 1:
                    addnewcontact(cfPtr);   
                        break;
                default: printf ("Choice Invalid\n");break;
        }
return 0;
     }
  }
}
          
         
int addnewcontact (FILE *fPtr)
{
FILE *cfPtr;
int choice;
int housenum;
char secc;
struct contact data = {"", "", "", "", ""};
printf ("\nAdding new contact: \n");
          printf ("First name: ");
          fscanf (stdin,"%s", data.firstname);
          printf ("Last name: ");
          fscanf (stdin, "%s", data.lastname);
          printf ("Address: ");
          fscanf (stdin, "%d %s %s", data.address);
          printf ("Postal code: ");
          fscanf (stdin, "%s %s", data.postalcode);
         if ( isvalidpostalcode (data.postalcode) != 0){
        printf ("This postal code is not valid, please enter a valid one.\n");
        printf ("Postal code: ");
        fscanf (stdin, "%s %s", data.postalcode);
        }  
          printf ("Phone number: ");
          fscanf (stdin, "%s", data.phone);
   
        fwrite (&data, sizeof (struct contact), 1, cfPtr);
        printf ("Would you like to enter a new contact? ");
 scanf ("%c", secc);
        if (secc = 'y'){
        addnewcontact (fPtr);
        }
        else{
          
    fclose (cfPtr);
    }
          
         
 return 0;
        
}
           
int isValidPostalCode(char pPtr[])  
{
   int length = (int)(strlen(pPtr));
        
   if (length == 7)
 if (isalpha(pPtr[0]) && isdigit(pPtr[1]) && isalpha(pPtr[2]) && isdigit(pPtr[4]) && isalpha(pPtr[5]) && isdigit(pPtr[6]))
      {
         if (pPtr[3] == ' ' || pPtr[3] == '-')
         {   
            return 1;
         }
      }
   }      
         
   return 0;
}

this is the entire program so far.. but i keep getting this error, i cant seem to solve it..

luna:~>cc addressbook.c
"addressbook.c", line 92: syntax error before or at: ]
"addressbook.c", line 106: cannot recover from previous errors
cc: acomp failed for addressbook.c

thanks again for all the help

You've got 1 too many braces in your last function:

}   // remove this one here   
         
   return 0;
}

oh no thats my fault, i forgot a brace after the

if (length == 7)

part.. theres supposed to be a brace after that..

ok, nevermind, i figured out the error and i made functions to validate the phone number and the postal code..

this is my code so far

#include <stdio.h>
#include <string.h>
#include <ctype.h>
 
struct contact {
char firstname [40];
char lastname [40];
char address [100];
char postalcode [6];
char phone[10];
};
int enterchoice (void);
int addnewcontact (FILE *fPtr);
int isvalidpostalcode (char pPtr[]);
int isvalidphone (char nPtr[]);
int main (void){
int choice;
printf ("\n *** Personal Contact Book v1.0 *** \n");
FILE *cfPtr;
if ((cfPtr = fopen ("contactlist.dat", "rb+")) == NULL){
printf ("File could not be opened.\n");
}
else{
while ((choice = enterchoice ()) != 6){
switch (choice){
case 1:
addnewcontact(cfPtr);
break;
default: printf ("Choice Invalid\n");break;
} 
return 0;
}
}
}
int enterchoice (void)
{
int menuchoice;
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");
printf (">");
scanf ("%d", &menuchoice);
 
return menuchoice;
}
int addnewcontact (FILE *fPtr)
{
FILE *cfPtr;
int choice;
int housenum;
char secc;
struct contact data = {"", "", "", "", ""};
 
 
printf ("\nAdding new contact: \n");
printf ("First name: ");
fscanf (stdin,"%s", data.firstname);
printf ("Last name: ");
fscanf (stdin, "%s", data.lastname);
printf ("Address: ");
fscanf (stdin, "%d %s %s", data.address);
printf ("Postal code: ");
fscanf (stdin, "%s", data.postalcode);
if (isvalidpostalcode (data.postalcode) == 0){
printf ("Invalid postal code, please enter a correct one.\n");
printf ("Postal code: ");
fscanf (stdin, "%s", data.postalcode);
} 
printf ("Phone number: ");
fscanf (stdin, "%s", data.phone);
if (isvalidphone (data.phone) == 0){
printf ("Invalid phone number, Please enter a 10-Digit phone number starting with the area code.\n");
printf ("Phone number: ");
fscanf (stdin, "%s", data.phone);
}
 
fseek (cfPtr, (data.phone - 1) * sizeof (struct contact), SEEK_SET);
fwrite (&data, sizeof (struct contact), 1, cfPtr);
printf ("\nWould you like to enter a new contact? ");
scanf ("%c", secc);
if (secc = 'y'){
addnewcontact (fPtr);
}
else{
 
fclose (cfPtr);
 
}
 
return 0;
 
}
 
int isvalidpostalcode(char pPtr[])
{
int length = (int)(strlen(pPtr));
if (length == 6){
if (isalpha(pPtr[0]) && isdigit(pPtr[1]) && isalpha(pPtr[2]) && isdigit(pPtr[3]) && isalpha(pPtr[4]) && isdigit(pPtr[5]))
{
return 1;
}
else{
return 0;
} 
} 
}
int isvalidphone (char nPtr[])
{ 
int length = (int)(strlen(nPtr));
 
if (length <= 10){
if (isdigit(nPtr[0]) && isdigit(nPtr[1]) && isdigit(nPtr[0]) && isdigit(nPtr[1]) && isdigit(nPtr[0]) && isdigit(nPtr[1]) && isdigit(nPtr[0]) && isdigit(nPtr[1]) $
{
return 1;
}
else{
return 0;
}
}
else {
return 0;
} 
}

but i keep getting a segmentation fault, and after debugging, i found out i need an fseek before my fwrite.. but i dont know how to use fseek with strings, can anyone help me???? thanks a bunch in advance!

ok, i got the seg fault and fixed it.. this is what ihave so far:

#include <stdio.h>
#include <string.h>
#include <ctype.h>


struct contact {
    char firstname [40];
    char lastname [40];
    char address [100];
    char postalcode [7];
    char phone[11];
}contact[10];

int enterchoice (void);
int addnewcontact (FILE *fPtr);
int isvalidpostalcode (char pPtr[]);
int isvalidphone (char nPtr[]);
void flush_in ();
int filewrite (FILE *xPtr);
int displaycontact (FILE *fPtr);
int i=1;

int main (void){

int choice;

printf ("\n *** Personal Contact Book v1.0 *** \n");

enterchoice();
}


int enterchoice (void)
{         
int choice;
FILE *cfPtr;
  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");
  printf (">");
  scanf ("%d", &choice);
  
      switch (choice){
        case 1: 
                    addnewcontact(cfPtr);
            break;
        case 2:
            displaycontact (cfPtr);
                break;
        case 4:
             filewrite(cfPtr);
                 break;
        case 6: break;
        default: printf ("Choice Invalid\n");break;
   
 }
return 0;
}

int addnewcontact (FILE *fPtr)
{
char choice = 'y';
    int z, y;  
FILE *outfile;

outfile = fopen ("contactlist.dat", "w");                    

while (choice == 'y'){
 printf ("\nAdding new contact: \n");
 printf ("First name: ");
 scanf("%s",contact[i].firstname);
 printf ("Last name: ");
 scanf("%s",contact[i].lastname);
 printf ("Address: ");
 flush_in();
 gets (contact[i].address);
 printf ("Postal code: ");
 scanf("%s",contact[i].postalcode);
        z = isvalidpostalcode (contact[i].postalcode);
while (z != 1){
    printf ("Invalid postal code, please enter a correct one.\n");
    printf ("Postal code: ");
    scanf("%s",contact[i].postalcode);
    flush_in();
    z = isvalidpostalcode (contact[i].postalcode);
    }
 printf ("Phone number: ");
 scanf("%s",contact[i].phone);
 flush_in();
y = isvalidphone (contact[i].phone);
while (y != 1){
    printf ("Invalid phone number, Please enter a 10-Digit phone number starting with the area code.\n");
    printf ("Phone number: ");
    scanf("%s",contact[i].phone);
    flush_in();
    y = isvalidphone (contact[i].phone);
    }
     

printf ("\nWould you like to enter a new contact? ");
scanf ("%c", &choice);
i++;

    }
    fclose (outfile);
enterchoice ();
 return 0;
  
}

int isvalidpostalcode(char pPtr[])
{
   int length = (int)(strlen(pPtr));

   if (length == 6){
      if (isalpha(pPtr[0]) && isdigit(pPtr[1]) && isalpha(pPtr[2]) && isdigit(pPtr[3]) && isalpha(pPtr[4]) && isdigit(pPtr[5]))
      {
    return 1;
    }
       else{
   return 0;
   }
 }
  else {
return 0;
 }
}

int isvalidphone (char nPtr[])
{
   int length = (int)(strlen(nPtr));
    
    if (length <= 10){
        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]))
        {
          return 1;
                }
        else{
            return 0;
        }
       }
    else {
    return 0;
    }
}

void flush_in (){
int ch;
while ((ch = fgetc (stdin))!= EOF && ch != '\n'){}
}

int filewrite (FILE *xPtr){

xPtr = fopen ("contactlist.dat", "w");

    fprintf (xPtr,"First name: %s\n", contact[i].firstname);
    fprintf (xPtr,"Last name: %s\n", contact[i].lastname);
    fprintf (xPtr,"Address: %s\n", contact[i].address);
    fprintf (xPtr,"Postal code: %s\n", contact[i].postalcode);
    fprintf (xPtr,"Phone number: %s\n", contact[i].phone);
fclose (xPtr);
    

printf ("\nContact information saved successfully!\n");
printf ("\n");
enterchoice ();
return 0;
   }
   
 
int displaycontact (FILE *fPtr){
 
    
 if ((fPtr = fopen ("contactlist.dat", "r")) == NULL){
 printf ("File Empty\n");
 }
 else{
 
 printf ("First name: %s\n", contact[i].firstname);
 printf ("Last name: %s\n", contact[i].lastname);
 printf ("Address: %s\n", contact[i].address);
 printf ("Postal code: %s\n", contact[i].postalcode);
 printf ("Phone number: %s\n", contact[i].phone);
 
 
 fclose (fPtr);
 }
 return 0;
 }

Does anyone know how i can pass my contact.firstname.. and all those variables and keep the values that i inputted into them? cuz everytime i try to display them, this is what i get:

*** Personal Contact Book v1.0 ***
1)Add New Contact.
2)Display Current Contacts.
3)Search for a contact.
4)Save Contacts to File.
5)Load Contacts from File.
6)Exit.
>2
First name: First
Last name:
Address:
Postal code:
Phone number:
luna:~>

im really stuck this time :|

EDIT: this result is.. ofcourse.. after inputting everything in the keyboard and saving the contact list. Any help is greatly appriciated!

You need to create a loop after the else statement that keeps grabbing lines from the data file until there's no more data. Inside that loop, you would parse out the individual fields and then print them out to the screen.

And stop using gets.

I don't see where you save the data in this loop... aren't you just throwing it out? (maybe I'm just missing something)

while (choice == 'y'){
    printf ("\nAdding new contact: \n");
    printf ("First name: ");
    scanf("%s",contact[i].firstname);
    printf ("Last name: ");
    scanf("%s",contact[i].lastname);
    printf ("Address: ");
    flush_in();
    gets (contact[i].address);
    printf ("Postal code: ");
    scanf("%s",contact[i].postalcode);
    z = isvalidpostalcode (contact[i].postalcode);
    while (z != 1){
        printf ("Invalid postal code, please enter a correct one.\n");
        printf ("Postal code: ");
        scanf("%s",contact[i].postalcode);
        flush_in();
        z = isvalidpostalcode (contact[i].postalcode);
    }
    printf ("Phone number: ");
    scanf("%s",contact[i].phone);
    flush_in();
    y = isvalidphone (contact[i].phone);
    while (y != 1){
        printf ("Invalid phone number, Please enter a 10-Digit phone number starting with the area code.\n");
        printf ("Phone number: ");
        scanf("%s",contact[i].phone);
        flush_in();
        y = isvalidphone (contact[i].phone);
    }
    
    
    printf ("\nWould you like to enter a new contact? ");
    scanf ("%c", &choice);
    i++;
    
}

You Can simply Check the length of area code and phone number. Area code should be 6 digits and Phone number should be 10 digits value. This is for only a simple Validation.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.