jeudi 4 juin 2015

Output random element from struct array

Im trying to output a random element from an array of structs on my Arduino. The struct looks like this

struct questionStructure {
    char question[7];
    int answer;
};

I call a method in my loop that holds a bunch of questions with answers and a random question is then supposed to be selected and shown on the display. That method looks like this

bool questionIsShown = false;
void randomQuestion()
{
    int random;
    struct questionStructure problems[4];
    char test[7];

    strcpy(test, "49 x 27");
    strcpy(problems[0].question, test);
    problems[0].answer = 1323;

    strcpy(test, "31 x 35");
    strcpy(problems[1].question, test); 
    problems[1].answer = 1085;

    strcpy(test, "47 x 37");
    strcpy(problems[2].question, test); 
    problems[2].answer = 1739;

    strcpy(test, "46 x 15");
    strcpy(problems[3].question, test); 
    problems[3].answer = 690;

    strcpy(test, "24 x 29");
    strcpy(problems[4].question, test); 
    problems[4].answer = 696;

    if(questionIsShown==false) {
        random = rand() % 4 + 0;
        lcd.setCursor(0,1);
        lcd.print(problems[random].question);
        questionIsShown=true;
    }

Im not sure what im doing wrong, but even if instead of the above use lcd.print(problems[0].question); the display shows multiple questions from the struct array. As an example, with the above the display shows 49 x 27+X31 x 35<- Where the X is some wierd looking symbol.

What am i doing wrong?




Aucun commentaire:

Enregistrer un commentaire