1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 | #include <stdio.h>
#include <stdlib.h>
#include <stdbool.h>
#include <assert.h>
#include <stdarg.h>
#include "argument_printer.h"
#include "stdbool.h"
// You are free to copy/adapt code here
// word that cannot be printed in argument_printer
static const char* _FORBIDDEN_WORD = "Apple";
/*
int _are_strings_same(char* first_str, char* second_str) {
int i;
for (i = 0; first_str[i] && second_str[i]; i++)
if (first_str[i] != second_str[i]) return 0;
if (first_str[i] != second_str[i]) return 1;
return 0;
}*/
// trying to fix a bug in _are_strings_same
static bool _are_strings_same(const char* first_str, const char* second_str) {
int shorter_str_len = 0;
for (; first_str[shorter_str_len] != '\0'
&& second_str[shorter_str_len] != '\0'; shorter_str_len++) {
if (first_str[shorter_str_len] != second_str[shorter_str_len]) {
return false;
}
}
// check if string are same length
// did we hit null one one string but not the other
if (first_str[shorter_str_len] == second_str[shorter_str_len]) {
return true;
}
return false;
}
void print_arguments(char* arguments, ...) {
va_list more_args;
va_start(more_args, arguments);
for (int arguments_idx = 0;
arguments[arguments_idx] != '\0'; arguments_idx++) {
// cannot declare inside the switch for technical reasons
int int_arg;
char* str_arg; // stores the value of string arguments
char char_arg; // stores the value of an char argument
float float_arg;
int rounded_down_float;
switch(arguments[arguments_idx]) {
case 'd':
int_arg = va_arg(more_args, int);
if (int_arg < 0) {
int sum = int_arg + 100;
printf("Negative Int %d\n", sum);
} else {
printf("Int %d\n", int_arg);
}
break;
case 's':
str_arg = va_arg(more_args, char*);
if (!_are_strings_same(str_arg, _FORBIDDEN_WORD)) {
printf("String %s\n", str_arg);
} else {
printf("Redacted\n");
printf("Cannot print the forbidden word\n");
}
break;
case 'c':
char_arg = va_arg(more_args, int);
printf("Char %c\n", char_arg);
break;
case 'f':
float_arg = va_arg(more_args, double);
printf("Float %f\n", float_arg);
rounded_down_float = float_arg;
printf("Rounded down %d\n", rounded_down_float);
}
}
va_end(more_args);
}
/* vim: set tabstop=4 shiftwidth=4 fileencoding=utf-8 noexpandtab: */
|
© Copyright 2022 Alexander J. Quinn This content is protected and may not be shared, uploaded, or distributed.