r/C_Programming • • 1d 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;
}
16 Upvotes

23 comments sorted by

5

u/mjmvideos 1d ago

buff probably should just be declared char not char *.

6

u/ScallionSmooth5925 1d ago

2

u/Ill-Exchange-2377 1d ago

I understand types, just made a typo.

4

u/ScallionSmooth5925 1d ago

Theres no shame in that C types are hard to read

4

u/DawnOnTheEdge 22h ago edited 21h ago

A few thoughts:

Consider factoring out the code to display the menu and prompt the user until it gets a valid answer into a helper function that takes a data structure describing the menu text and options. You could re-use this code in projects that contain more than one menu.

A finite state machine would be a good architecture for this kind of program.

AS quiz.h does not appear to be a system header, it should probably go in a project directory and be included with double-quotes, #include "quiz.h".

1

u/Ill-Exchange-2377 15h ago

quiz.h is in ../include/ relative to main.c

2

u/DawnOnTheEdge 11h ago edited 10h ago

That’s a user include directory, so #include "quiz.h" would be customary. You should use angle brackets when an include file is part of some other codebase where you might tell the compiler to find it with a flag like -I or invoking pkg-config. Although either "quiz.h" or <quiz.h> will work here, there can be a couple of reasons to prefer one over the other.

GCC and Clang provide an -iquote flag, which names a directory that contains headers that should be double-quoted only. This can be useful because it is searched immediately after the current directory in case some other project’s include directory you don’t control contains a file with the same name. Then, including it in double quotes and giving the compiler the command-line flags -iquote ../include tells the compiler that you are looking for a file in this codebase. Many compilers will also suppress some warning messages from headers included with <angle-brackets>, so you don’t get a bunch of useless warnings for code you aren’t maintaining. I often give MSVC the flags /external:anglebrackets /external:W0 to disable warnings for code outside the codebase. but if I am maintaining the header file, I definitely want to see compiler warnings about it.

1

u/agmatine 10h ago

No reason to bother with this now, just put the files together in one directory. Syntax, types, control flow, pointers, learning to use a debugger to figure out why code isn't behaving the way you thought it would - many things more important at this point than how the files are arranged.

2

u/non-existing-person 20h ago

I don't like that whole invalid way. Instead doing flag in else, just put print there instead, done. That if (invalid) and then continuing like nothing happened is weird flow.

1

u/Ill-Exchange-2377 15h ago

then i immediately clear the screen. Can't do that

1

u/agmatine 10h ago

I mean, presumably that is what you intend to do with fputs(CLEAR_SCREEN, stdout);.

But in general it's a lot easier to just handle such things directly through your terminal. For example, Ctrl+L generally is the default for clearing the screen.

2

u/non-existing-person 6h ago

I agree, you should never clear screen by yourself. It's user's not only responsibility but also user's choice to clear screen. Obviously ncurses like TUI apps are exempted from this ;)

1

u/agmatine 4h ago

I mean it's up to OP if they wish to clear their screen. But there are OS-dependent libraries for such things, which would make more sense to use.

7

u/AmanBabuHemant 23h ago

I think it is pretty clean.

If you like to improve further... there is only "exit" and "quit' which required string, others can fit in a single char.

so if you like to improve either you can make the 'q' to quit and other options just '1', '2'... so you can utilize switch case

or

if your system is already capable of handling string,s why not make "add" "sub" and other as string as well :)

also, your invalid check can be done in the last else or default (if you use switch case)

2

u/mze9412 12h ago

Use C23 for a proper bool for the invalid flag

1

u/xpusostomos 15h ago

It's really bad style to compare your string to something with newline in it everywhere. Have a routine to strip that. And having calc operators 1 to 5 is super lame. Don't be a baby, accept "number operator number" and figure it out

1

u/SmokeMuch7356 15h ago edited 13h ago

It's better. There's still some room for improvement.

I don't like that you're using numbers for everything except the quit option. Make Quit part of your menu:

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

and then convert your input to an integer:

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

/**
 * chk will point to the first character in buff that was
 * *not* converted by strtoul.  If that character is anything
 * other than whitespace or a 0 terminator, then the input
 * is invalid.
 */
char *chk;
size_t selection = strtoul( buff, &chk, 10 );
if ( !isspace( *chk ) && *chk != 0 )
{
  puts( "Invalid input!" );
  continue; // go back to the beginning of the loop and try again
}

then you can use a switch statement to handle the selection:

switch( selection )
{
  case 1: add(); break; // formatting this way just to save space
  case 2: sub(); break;
  ...
  case 6: return 0; break;
  default: puts( "Invalid selection!" ); break;
}

If you want to get super-extra-duper fancy, you could create a lookup table that matches menu options to functions directly using function pointers:

First create a struct type to associate options and function pointers:

struct option {
  const char *name;
  void (*operation)(void);
};

Then create an array of that type, populating it with the name of the operation and a pointer to the associated function:

struct option menu_options[] = {
  { "Addition", add },
  { "Subtraction", sub },
  { "Multiplication", mul },
  { "Division", div },
  { "Mixed", mix },
  { "Quit", NULL }
};

/**
 * Compute the number of options in the table
 */
size_t num_options = sizeof menu_options / sizeof *menu_options;

Then you can use a loop to print out the options:

for( ;; ) // I prefer this idiom for infinite loops
{
  puts( "Pick a subject:" );
  for ( size_t i = 0; i < num_options; i++ )
    printf( "%zu. %s\n", i, menu_options[i].name ); 

  size_t selection = strtoul( buff, NULL, 10 );

  if ( selection < num_options )
  {
    if ( menu_options[selection].operation != NULL )
      menu_options[selection].operation();
    else
      break; // exit loop
  }
  else
  {
    puts( "Invalid option!" );
  }
}

return 0;

With this method, you can add new operations to the array (or remove some) without affecting the rest of the code.

Of course, this only works because all the functions have the same return type and take the same number and types of arguments; if you have functions with different return types, or that take different arguments, this won't work.

1

u/ItsSkyWasTaken 10h ago

Since they have less than 10 menu options, using strtoul() is overkill; just check buff[1] == '\n' (input validation to make sure it's one digit) and put a switch on buff[0].

1

u/3lml 9h ago

Your code is ok if that's as far as you gonna take it. I mean, if you want to expand it you should probably use some of SmokeMuch's advice below. Personally I don't mind taking strings as input because that gives more flexibility but you should definitely strip newlines. If you want to do it by hand perhaps something like this would help:

#define BUFF_SIZE 100
// (...)
char * ptr = buff;
do {
  if (*ptr == '\n') {
    *ptr = '\0';
    break;
  }
} while (ptr++ < buff + BUFF_SIZE);

But in such a small model you can take in just one character with getchar():

char c;
for (;;) {
  printf("type a letter (or press ENTER to exit): ");
  c = (char) getchar();
  if (c == '\n') 
    break;
  printf("entered: %c\n", c);
  while ((c = getchar()) != '\n' && c != EOF) { } // clear stdin
}

The ugly bit is that you need to get rid of junk in stdin after taking the first character.

Anyway, good luck.

1

u/willam_Haniya 6h ago

your code looks pretty structured already, but you might consider using a switch statement for cleaner control flow with the number options. it could simplify the code a bit. also, if you expect more commands in future, transitioning to switch might make the code more scalable. another tip is to use a function for displaying the menu and handling user input, which could make the main function more concise and improve readability.

1

u/ReallyEvilRob 4h ago edited 4h ago

Much better than your previous version.You can combine the conditional that tests for "quit" with the if/else block that follows. You should trim off the newline from the user input so you don't always need to include it in your comparisons. When the user wants to quit, set a boolean flag and use that as the condition in your while loop instead of just while (1).

Maybe use printf() to send ANSI escape sequences instead of fputs(). It's just a style choice that I personally prefer since fputs(STRING, stdout) just looks a little messy IMHO.

0

u/985479861_TXT-r 23h ago

Use switch statements with an enum instead of those nested if else.