Bringing an NSString Problem to char

I want to pass my NSString to a constant char code is shown below:

NSString *date = @"12/9/2009"; char datechar = [date UTF8String] NSLog(@"%@",datechar); 

however it returns a warning assignment makes an integer from a pointer without casting and cannot correctly type char, can anyone tell me what the problem is?

+7
objective-c iphone
source share
5 answers

Try something else like this:

 NSString* date = @"12/9/2009"; char* datechar = [date UTF8String]; NSLog(@"%s", datechar); 

You need to use char * instead of char, and you need to print the C lines using% s, not% @ (% @ for objective-c id types).

+27
source share

I think you want to use:

 const char *datechar = [date UTF8String]; 

(pay attention to * there)

+6
source share

There are 2 problems in your code:

1) "char datechar ..." is a one-character character that will contain only one char / byte, and will not contain the entire array that you create from your date / string object. Therefore, your string must have (*) in front of the variable in order to store several characters, and not just one.

2) After the above correction, you will still receive a warning about (char *) vs (const char *), so you will need to "distinguish" because they technically match the results. Change the line:

char datechar = [date UTF8String];

in

char *datechar = (char *)[date UTF8String];

The notification (char *) after the = sign tells the compiler that the expression will return (char *), not the default (const char *).

I know that you already noted the answer earlier, but I thought I could do my part to explain the problems and how to fix it in more detail.

Hope this helps.

Regards Haider

+2
source share

I would add * between char and datechar (and% s instead of% @):

 NSString *date=@"12/9/2009"; char * datechar=[date UTF8String]; NSLog(@"%s",datechar); 
+1
source share

I have long endured converting NSString to char for use for this function

 -(void)gpSendDTMF:(char) digit callID: (int)cid; 

I tried every answer of this question / a lot of google search, but it did not work for me.

Finally, I have a solution.


Decision:

 NSString *digit = @"5"; char dtmf; char buf[2]; sprintf(buf, "%d", [digit integerValue]); dtmf = buf[0]; 
0
source share

All Articles