Home > Software design >  C Programming - can't close if loop properly
C Programming - can't close if loop properly

Time:11-14

I'm doing a cyber forensics course and part of the course is reverse engineering. They expected us to know C. Oops. I've been coding in C for a grand total of about 16 hours now.

The assignment is to make a student grade calculator. I've done that. My problem is that I'm supposed to end the loop ONLY if the name UNKNOWN is entered as the student's name. I can do it with the character 'q', but not with a string.

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

int main() {
  float grade1, grade2, grade3, grade4; //defining variables//
  char name[32]; //defining variables//

  //This section introduces the quiz calculator and asks for the student's name//
  printf("Welcome to the Student Quiz Calculator Program\n");

  while (1) { //While loop set to always true so it repeats//
    printf("Enter a student name. Enter 'q' to quit: \n"); //Asking for user input//
    scanf("%s", &name); //Take input and assign it as 'name'//

    if (*name == 'q') { //If name matches 'q' terminate program//
      printf("Thanks for using the calculator. Bye!\n");
      break;

    } else {
    printf("Enter quiz grade 1: "); //Asking for user input//
    scanf("%f", &grade1);
    printf("Enter quiz grade 2: "); //Asking for user input//
    scanf("%f", &grade2);
    printf("Enter quiz grade 3: "); //Asking for user input//
    scanf("%f", &grade3);
    printf("Enter quiz grade 4: "); //Asking for user input//
    scanf("%f", &grade4);

    float average = (grade1   grade2   grade3   grade4) / 4; //Performing calculations//
    printf("%s, with grades of %.0f, %.0f, %.0f, and %.0f, your quiz average is %0.2f!\n", name, grade1, grade2, grade3, grade4, average);
    }
  }

CodePudding user response:

Your use of *name is equivalent to name[0]. That's why your check for 'q' works, because you are able to correctly check if the first character in the name array is the character q.

If you want to see if name is equal to some string, you want to use strcmp():

if(strcmp(name, "UNKNOWN") == 0) {
    printf("Thanks for using the calculator. Bye!\n");
    break;
}
  •  Tags:  
  • c
  • Related