Man Person
Man Person

Reputation: 1130

C Random, having problems

void getS(char *fileName){
    FILE *src;
    if((src = fopen(fileName, "r")) == NULL){
        printf("%s %s %s", "Cannot open file ", fileName, ". The program is now ending.");
        exit(-1);
    }
    //char *get = " ";      

    int c = 1;
    char ch = 'x';
    while(ch!=EOF) {
        ch = fgetc(src);
        if(ch == '\n')  c++;
    }
    fseek(src, 0, SEEK_SET);
    int random = rand() % c;
    int i = 0;
    for(i = 0; i < random; i++){
        while(ch != '\n'){
            ch = fgetc(src);
        }
    }
    do{
        ch = fgetc(src);
        if(ch != '\n' && ch != EOF){
            printf("%c", ch);
        }
    }while(ch != '\n' && ch != EOF);
    printf("%c", '\n');
    fclose(src);
}

So this is my function that grabs a file and prints out a random word in the file if each word is separated by a new line.

Question 1: Why is the random having preference to the first 2 words?

Question 2: How would I make it so I can use this function multiple times without doing the printf("%c", '\n'); because if I don't have that in the end the previous function call just overwrites the old one.

Thanks in advance, I've been asking a bit today thanks for all the help stackoverflow! :)

P.S. using srand(time(NULL));

Upvotes: 0

Views: 111

Answers (2)

Vaughn Cato
Vaughn Cato

Reputation: 64308

Look at the logic here:

    for(i = 0; i < random; i++){
        while(ch != '\n'){
            ch = fgetc(src);
        }
    }

Once you hit a newline, you won't read any more characters, so you're always going to print either the first or second line.

You can fix it like this:

    for(i = 0; i < random; i++){
        ch = fgetc(src); // start by reading the first character on the line
        while(ch != '\n'){
            ch = fgetc(src);
        }
    }

Jim Balter also notes that ch would best be declared as an int. This is because EOF is not considered to be a regular character.

Upvotes: 2

ASB
ASB

Reputation: 344

without printf("%c","\n"); line at the end it is working fine...

Upvotes: 0

Related Questions