casting a NSString to char problem

匿名 (未验证) 提交于 2019-12-03 03:06:01

问题:

i want to casting my NSString to a constant char the code is shown below :

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

however it return the warning assignment makes integer from pointer without a cast and cannot print the char properly,can somebody tell me what is the problem

回答1:

Try something more like this:

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

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



回答2:

I think you want to use:

const char *datechar = [date UTF8String]; 

(note the * in there)



回答3:

Your code has 2 problems:

1) "char datechar..." is a single-character, which would only hold one char / byte, and wouldn't hold the whole array that you are producing from your date/string object. Therefore, your line should have a (*) in-front of the variable to store multi characters rather than just the one.

2) After the above fix, you would still get a warning about (char *) vs (const char *), therefore, you would need to "cast" since they are technically the same results. Change the line of:

char datechar = [date UTF8String];

into

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

Notice (char *) after the = sign, tells the compiler that the expression would return a (char *) as opposed to it's default (const char *).

I know you have already marked the answer earlier however, I thought I could contribute to explain the issues and how to fix in more details.

I hope this helps.

Kind Regards Heider



回答4:

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

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


回答5:

I was suffering for a long time to convert NSString to char to use for this function

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

I have tried every answer of this question/many things from Google search but it did not work for me.

Finally I have got the solution.


Solution:

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


标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!