开发者

Accept string values in NSArray from the user

开发者 https://www.devze.com 2023-01-11 16:45 出处:网络
hi i want to accept string values into the object of NSArray at run time from the user heres what i tried

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];
0

精彩评论

暂无评论...
验证码 换一张
取 消