0

I'm new to c and part of our online exercises is to finish a code that asks for input and if it matches password1 then prints the correct password. the functionality of the code below is right but the autograder of the exercise tells me that it uses too much CPU. Any idea why? I think it has to do with the way I check for feof.

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

#define MAX_BUFFER_SIZE 80

/* Prompts user for password, waits for correct password */
void wait_for_correct_password(void) {
    char buffer[MAX_BUFFER_SIZE];

    printf("Enter password: ");

    char* password = fgets(buffer, MAX_BUFFER_SIZE, stdin);
    // Write your while loop here

    while (!feof(stdin)){

        while (strcmp(password, "password1\n" )!=0 ) { 

            fgets(buffer, MAX_BUFFER_SIZE, stdin);
        }
        printf("Password correct!\n");
        break;
    }
    
}

int main(int argc, char** argv){
    wait_for_correct_password();
}
quint k
  • 13
  • 4
  • 1
    https://stackoverflow.com/questions/5431941/why-is-while-feoffile-always-wrong – Yunnosch Jun 24 '22 at 11:33
  • 1
    Using `while (!feof(file))` is always wrong. You don't check for EOF at all in the inner loop, so if the input finishes without the correct password, your program goes into a tight loop using way too much CPU time. – Jonathan Leffler Jun 24 '22 at 11:33

0 Answers0