Sparkm4n
Sparkm4n

Reputation: 644

random characters in c

I wrote a program that attempts to "guess" a word by randomly choosing characters. However, my program is printing characters that are not in my character list. What is going on here?

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int main(){

    int index, i;
    time_t t;
    char characters[] = "bdefgir";
    char word[] = "friedberg";
    srand((unsigned)time(&t));
    char result[9] = {0};

    while(strcmp(result, word) != 0){

        for (i = 0; i < 9; i++) {
            index = rand() % 8;
            result[i] = characters[index];
        }
        printf("Result:\t%s\n", result);

    }

    return 0;

}

Upvotes: 0

Views: 2971

Answers (1)

Keammoort
Keammoort

Reputation: 3075

Your misspelled variable wort it should be word. Also you have to have result array containing 9 characters (like your word "friedberg") and ending with a '\0' character (so total number of characters is in fact 10).

The correct solution would be:

#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#include <string.h>

int main() {

    int index, i;
    time_t t;
    char characters[] = "bdefirg";

    char word[] = "friedberg";

    srand((unsigned) time(&t));
    char result[10];
    result[9] = '\0';

    while (strcmp(result, word) != 0) {

        for (i = 0; i < 9; i++) {
            index = rand() % 7;
            result[i] = characters[index];
        }
        printf("Result:\t%s\n", result);

    }

    return 0;

}

Upvotes: 3

Related Questions