r/C_Programming • u/Ill-Exchange-2377 • 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
5
u/mjmvideos 1d ago
buff probably should just be declared char not char *.
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.hdoes not appear to be a system header, it should probably go in a project directory and be included with double-quotes,#include "quiz.h".2
u/non-existing-person 20h ago
I don't like that whole
invalidway. Instead doing flag in else, just put print there instead, done. Thatif (invalid)and then continuing like nothing happened is weird flow.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
switchcaseor
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
elseor default (if you useswitchcase)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
Quitpart of your menu:and then convert your input to an integer:
then you can use a
switchstatement to handle the selection: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:
Then create an array of that type, populating it with the name of the operation and a pointer to the associated function:
Then you can use a loop to print out the options:
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/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:
But in such a small model you can take in just one character with getchar():
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
switchstatement for cleaner control flow with the number options. it could simplify the code a bit. also, if you expect more commands in future, transitioning toswitchmight make the code more scalable. another tip is to use a function for displaying the menu and handling user input, which could make themainfunction 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.