ex-03: Added solution for rgb converter
This commit is contained in:
parent
5b4dc03763
commit
cfadb53fa9
90
exercise-03-rgb/main.c
Normal file
90
exercise-03-rgb/main.c
Normal file
@ -0,0 +1,90 @@
|
||||
#include <ctype.h>
|
||||
#include <stdio.h>
|
||||
#include <stdlib.h>
|
||||
#include <string.h>
|
||||
#include <stdbool.h>
|
||||
|
||||
#ifdef __PROGTEST__
|
||||
#define debug(...) ((void)0)
|
||||
#else
|
||||
#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;
|
||||
}
|
||||
|
||||
int invalid_input() {
|
||||
printf("Nespravny vstup.\n");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
int main() {
|
||||
char* input = NULL;
|
||||
size_t len;
|
||||
|
||||
int rgb[3];
|
||||
|
||||
printf("Zadejte barvu v RGB formatu:\n");
|
||||
|
||||
ssize_t chars_read = getline(&input, &len, stdin);
|
||||
|
||||
if(chars_read == -1) {
|
||||
printf("Failed to read from stdin\n");
|
||||
return EXIT_FAILURE;
|
||||
}
|
||||
|
||||
char* dst = input;
|
||||
for(char * src = input; *src; src++) {
|
||||
if(!isspace(*src)) {
|
||||
*dst++ = *src;
|
||||
}
|
||||
}
|
||||
*dst = '\0';
|
||||
|
||||
int trimmed_len = strlen(input);
|
||||
if(strncmp(input, "rgb(", 4) != 0 || input[trimmed_len - 1] != ')') {
|
||||
debug("%s not in rgb(xxx) format", input);
|
||||
return invalid_input();
|
||||
}
|
||||
|
||||
input[trimmed_len - 1] = '\0';
|
||||
char* slice = input + 4;
|
||||
|
||||
char* token = strtok(slice, ",");
|
||||
|
||||
for(int i = 0; i < 3; i++) {
|
||||
if(token == NULL) {
|
||||
debug("Too few numbers");
|
||||
return invalid_input();
|
||||
}
|
||||
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();
|
||||
}
|
||||
|
||||
printf("#%02X%02X%02X\n", rgb[0], rgb[1], rgb[2]);
|
||||
return EXIT_SUCCESS;
|
||||
}
|
Loading…
x
Reference in New Issue
Block a user