Ring-Jarvi February 2016

Take user input from scanf and add to a array?

I'm trying to create an array of questions that I will enter into a trivia game. I'm having problems with scanf and adding the whole questions to the array. It will only enter the first word of my question

Example: I want to input "How many bases in baseball?" and have it entered into allquestions[0], then be asked for the next questions to be entered into the array, but what I get is just "How" from scanf. I think I need to transfer the scanf input into a string then addobject into the array. Any help would be much appreciated. I'm very new to this.

        NSMutableArray *allquestions = [[NSMutableArray alloc]init];

        char *questions[200];
        int i =0;
        for (i = 0; i < 20; i++) {
            NSLog(@"Next question?");
            scanf("%s",&questions);

            NSLog(@"%s", &questions);
            [allquestions addObject:questions[i]];
    }

Answers


Shehzad Ali February 2016

I hope it will work for you:

NSMutableArray *allquestions = [[NSMutableArray alloc]init];
char questions[20][200]; // Can store 20 questions each of length 200

//input each question
for(int i=0;i<20;i++)
{
   NSLog(@"Next question?");
   scanf("%[^\n]%*c",questions[i]);
   NSString *questionString = [NSString stringWithCString:questions[i] encoding:NSASCIIStringEncoding];

   [allquestions addObject:questionString];

}

//Print each string
for(int i=0;i<20;i++)
{
   printf("%s",questions[i]);
   printf("\n");
}

Post Status

Asked in February 2016
Viewed 1,844 times
Voted 12
Answered 1 times

Search




Leave an answer