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 <stdlib.h>
#include <string.h>
@ -10,14 +9,8 @@
#define debug(fmt, ...) fprintf(stdout, "[DEBUG %s:%d %s()] " fmt "\n", __FILE__, __LINE__, __func__, ##__VA_ARGS__)
#endif
bool is_numeric(const char* str) {
if(*str == '\0') return false;
for(;*str; str++) {
if(!isdigit(*str))
return false;
}
return true;
bool is_in_rgb_range(int color) {
return color >= 0 && color <= 255;
}
int invalid_input() {
@ -26,73 +19,22 @@ int invalid_input() {
}
int main() {
char* input = NULL;
size_t len;
int rgb[3];
int r = -1, g = -1, b = -1;
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) {
printf("Failed to read from stdin\n");
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);
if(inputs_read != 3) {
debug("Not enough inputs read");
return invalid_input();
}
input[trimmed_len - 1] = '\0';
char* slice = input + 4;
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");
if(!is_in_rgb_range(r) || !is_in_rgb_range(g) || !is_in_rgb_range(b)) {
debug("Number not in range of rgb [0, 255]");
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;
}