ex-03: Simplified and optimized code

This commit is contained in:
Tomáš Kléger 2025-10-10 14:39:35 +02:00
parent fe80bfc2fe
commit f790d3968b

View File

@ -1,4 +1,3 @@
#include <ctype.h>
#include <stdio.h> #include <stdio.h>
#include <stdlib.h> #include <stdlib.h>
#include <string.h> #include <string.h>
@ -10,14 +9,8 @@
#define debug(fmt, ...) fprintf(stdout, "[DEBUG %s:%d %s()] " fmt "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__) #define debug(fmt, ...) fprintf(stdout, "[DEBUG %s:%d %s()] " fmt "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__)
#endif #endif
bool is_numeric(const char* str) { bool is_in_rgb_range(int color) {
if(*str == '\0') return false; return color >= 0 && color <= 255;
for(;*str; str++) {
if(!isdigit(*str))
return false;
}
return true;
} }
int invalid_input() { int invalid_input() {
@ -26,73 +19,22 @@ int invalid_input() {
} }
int main() { int main() {
char* input = NULL; int r = -1, g = -1, b = -1;
size_t len;
int rgb[3];
printf("Zadejte barvu v RGB formatu:\n"); printf("Zadejte barvu v RGB formatu:\n");
ssize_t chars_read = getline(&input, &len, stdin); int inputs_read = scanf(" rgb ( %d , %d , %d )", &r, &g, &b);
if(chars_read == -1) { if(inputs_read != 3) {
printf("Failed to read from stdin\n"); debug("Not enough inputs read");
return EXIT_FAILURE;
}
// Strip out any whitespaces
char* dst = input;
for(char * src = input; *src; src++) {
if(!isspace(*src)) {
*dst++ = *src;
}
}
*dst = '\0';
int trimmed_len = strlen(input);
// Check whether the provided input
// starts with rgb(
// and ends with )
if(strncmp(input, "rgb(", 4) != 0 || input[trimmed_len - 1] != ')') {
debug("%s not in rgb(xxx) format", input);
return invalid_input(); return invalid_input();
} }
input[trimmed_len - 1] = '\0'; if(!is_in_rgb_range(r) || !is_in_rgb_range(g) || !is_in_rgb_range(b)) {
char* slice = input + 4; debug("Number not in range of rgb [0, 255]");
char* token = strtok(slice, ",");
for(int i = 0; i < 3; i++) {
// strtok reached end prematurely
if(token == NULL) {
debug("Too few numbers");
return invalid_input();
}
// Not a number
if(!is_numeric(token)) {
debug("%s is not a number", token);
return invalid_input();
}
int parsed = atoi(token);
if(parsed < 0 || parsed > 255) {
debug("%d out of RGB range", parsed);
return invalid_input();
}
rgb[i] = parsed;
token = strtok(NULL, ",");
}
if(token != NULL) {
debug("Too many numbers");
return invalid_input(); return invalid_input();
} }
printf("#%02X%02X%02X\n", rgb[0], rgb[1], rgb[2]); printf("#%02X%02X%02X\n", r, g, b);
return EXIT_SUCCESS; return EXIT_SUCCESS;
} }