Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Converting char array into NSString object

As per my assignment I have to take in input from a user via a console to be used with NSString.

At the moment I have

char* name[100]; // declaring char array
NSString* firstName; // declaring the NSString

printf("Please enter first name \n");
printf("=> ");
scanf("%s", &name);

firstName = [NSString stringWithCString:name encoding:NSASCIIStringEncoding];

This works, however I am getting this warning

Incompatible pointer types sending 'char [100]' to parameter of type 'const char '

I don't want to be having these errors coming up in the code, I would like to also mention I'm using Xcode 4.2.

Can anyone explain to me why I'm getting these errors, and if I can possibly overcome them?

Many thanks in advance!

like image 898
David Evans Avatar asked Feb 18 '12 16:02

David Evans


2 Answers

As printed with NSLog is assigned to initialize a NSString.

NSLog(@"%s", arrayChar);
NSString *str = [NSString stringWithFormat:@"%s", arrayChar];
NSLog(@"Array to String: %@",str);
like image 79
Jaime Avatar answered Nov 15 '22 00:11

Jaime


Change this:

char* name[100];

to

char name[100];

The first form creates an array of 100 pointers to char. The second one creates an array of 100 char elements. What might be confusing, is that name in that last case, is in fact a pointer, pointing to the first of these 100 char elements.

like image 45
mvds Avatar answered Nov 15 '22 01:11

mvds