hi i want to accept string values into the object of NSArray at run time from the user heres what i tried
-(void)fun
{
NSArray *arr = [[NSArray alloc]init];
for(int i =0;i<3;i++)
{
scanf("%s",&arr[i]);
}
printf("Print values\n");
for(int j =0; j<3;j++)
{
printf("\n%s",arr[j]);
}
}
i am gett开发者_StackOverflow中文版ing an error can you please help me out regarding this and is their any alternative to scanf in objective c. Thank you
scanf()
with a %s
format will read the string into a C array, not an NSArray
object. You need to read the string into a C array, then make an NSString
object to add to your NSArray
. You also need to have a mutable array to make your code work. Example:
NSMutableArray *arr = [[NSMutableArray alloc] initWithCapacity:3];
for (int i = 0; i < 3; i++)
{
char buf[100];
scanf("%s", buf);
NSString *str = [NSString stringWithCString:buf encoding:NSASCIIStringEncoding];
[arr addObject:str];
}
You can use NSLog()
to print your strings later on.
use NSMutableArray
instead;
than you can use also
[arr addObject:tempVar];
精彩评论