Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <stdio.h>
- #include <string.h>
- #include <stdlib.h>
- #define BUFFER_SIZE 20 //It's said that thecolor has at most 20 character
- //A number lower than 1000 also has less than 20 characters
- typedef struct {
- char color[BUFFER_SIZE + 1]; //+1 for /0
- float radius; //When we divide the diameter by 2, we may endup with floats
- } cup_t;
- int read_cups(cup_t *cups){
- char buffer[2*BUFFER_SIZE + 2]; //At most 20chars + 1 space + 20chars + 1 /0
- char *buff1, *buff2;
- int n_cups, num;
- scanf("%d\n", &n_cups);
- for(int read_cups=0; read_cups<n_cups; ){
- fgets(buffer, 2*BUFFER_SIZE + 2, stdin);
- if( buffer == NULL ){ //Validate input
- printf("Invalid input. \n");
- continue;
- }
- buff1 = strtok(buffer, " ");
- buff2 = strtok(NULL, "\n");
- if(buff1 == NULL || buff2 == NULL){ //Validate input
- printf("Invalid input. \n");
- continue;
- }
- num = atoi(buff1);
- if( num != 0 ){ //If successful convertion on buff1, then the diameter comes first
- cups[read_cups].radius = num/2.0;
- strcpy( cups[read_cups].color, buff2 );
- read_cups++;
- }
- else{ //A failed convertion means the buff1 is not an int, so it must be a color, meaning that the radius should be in buff2
- strcpy( cups[read_cups].color, buff1 );
- num = atoi( buff2 );
- if( num != 0){ //Validate input
- cups[read_cups].radius = num;
- read_cups++;
- }
- else{
- printf("Invalid input. \n");
- continue;
- }
- }
- }
- return n_cups;
- }
- int compare_cup_t(const void * p_a, const void * p_b) {
- cup_t *a = (cup_t *)p_a;
- cup_t *b = (cup_t *)p_b;
- return (a->radius - b->radius);
- }
- int main(void){
- cup_t cups[20]; //It's said we have at most 20 cups
- int n_cups = read_cups( cups );
- qsort(cups, n_cups, sizeof(cup_t), compare_cup_t);
- printf("Sorted:\n");
- for(int i=0; i<n_cups; i++){
- printf("%s %f\n", cups[i].color, cups[i].radius);
- }
- return 0;
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement