r/C_Programming • • 14d ago

Is my code better

I shared some code earlier, and got some criticism, as well as making improvements of my own

Is it better? And where does it still fall short?

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

#include <quiz.h>

#define CLEAR_SCREEN "\033[2J\033[H"

int main(void) {
  char buff[100];
  int invalid = 0;

  while (1) {
    fputs(CLEAR_SCREEN, stdout);

    puts("Pick a subject:");
    puts("1: Addition");
    puts("2: Subtraction");
    puts("3: Multiplication");
    puts("4: Division");
    puts("5: Mixed");

    if (invalid) {
      puts("Please enter valid input");
      invalid = 0;
    }

    puts("Pick a number 1-5, or use 'quit' or 'exit' to quit");

    if (fgets(buff, sizeof(buff), stdin) == NULL) {
      puts("Failed, exiting");
      return 1;
    }


    if (strcmp(buff, "quit\n") == 0 || strcmp(buff, "exit\n") == 0) {
      fputs(CLEAR_SCREEN, stdout);
      break;
    }

    if (strcmp(buff, "1\n") == 0) {
      add();
    } else if (strcmp(buff, "2\n") == 0) {
      sub();
    } else if (strcmp(buff, "3\n") == 0) {
      mul();
    } else if (strcmp(buff, "4\n") == 0) {
      divs();
    } else if (strcmp(buff, "5\n") == 0) {
      mix();
    } else {
      invalid = 1;
    }
  }

  return 0;
}
18 Upvotes

26 comments sorted by

View all comments

8

u/mjmvideos 14d ago

buff probably should just be declared char not char *.

6

u/ScallionSmooth5925 14d ago

4

u/Ill-Exchange-2377 14d ago

I understand types, just made a typo.

4

u/ScallionSmooth5925 14d ago

Theres no shame in that C types are hard to read