Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

C Programming – can't close if loop properly

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);
    }
  }

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading