Hey, I’m new to Objective-C and as well as programming with Cocoa at all.. anyways my code looks like:
int main(int argc, char *argv[])
{
printf("how many address would you like to input?\n");
int numAddresses;
scanf("%i", &numAddresses);
char *inputString;
NSMutableArray * arrayOfBooks = [NSMutableArray array];
for (int i = 0; i < numAddresses; ++i) {
book * f = [[book alloc] init];
printf("Please input the name of contact %i\n", i+1);
scanf("%s",inputString);
[f setName: inputString];
printf("Please input the address of contact %i\n", i+1);
scanf("%s", inputString);
[f setAddress: inputString];
printf("Please input the birthday of contact %i\n", i+1);
scanf("%s", inputString);
[f setBirthday: inputString];
printf("Please input the phone number of contact %i\n", i+1);
scanf("%s", inputString);
[f setPhoneNumber: inputString];
[f print];
[arrayOfBooks addObject:f];
[f release];
}
for(int i = 0; i < numAddresses; i++){
[arrayOfBooks[i] print];
}
return 0;
}
I’m basically just making an address book. When I input the first name, it throws an “EXC_BAD_ACCESS” error. Why?
#import "book.h"
@implementation book
-(void) setName: (char*) nameInput{
name = nameInput;
}
-(void) setAddress: (char*) addressInput{
address = addressInput;
}
-(void) setPhoneNumber: (char*) phoneNumberInput{
phoneNumber = phoneNumberInput;
}
-(void) setBirthday: (char*) birthdayInput{
birthday = birthdayInput;
}
-(void) print{
printf("Name: %s\n", name);
printf("Address: %s\n", address);
printf("Phone Number: %s\n", phoneNumber);
printf("Birthday: %s\n", birthday);
}
@end
EDIT: I no longer get the error.. but now I have a new problem. It prompts me for the name input, then instantly prompts me for the address input before I have a chance to do anything. Why could this be happening?
A good idea is to use
fgets()instead ofscanf(). Any whitespace (spaces, tabs, newlines etc.) will causescanf()to stop parsing, which—based on the input you are trying to obtain—is probably not what you want.Use
fgets()like this: