This is a pretty simple FizzBuzz variant. I'm more interested in my use of C (this is my first bit of C code) than I am in my actual FizzBuzz implementation, although I'm always open to suggestions.
In particular I'm pretty certain that my string manipulations are horrific, but I don't really know where to start improving.
I've also added in a little debug utility that I've created, with the purpose of implementing some stuff with header files, as those are completely new to me. All it does is toggle whether a print method will do anything, based on a global flag; I'm not sure if this is actually useful, or if I'm overlooking a better equivalent.
FizzBuzz Source
#include <string.h>
#include "debug_util.c"
void evaluate(char*, int, int, char*);
const int MAX_STRING_LEN = 17;
const int MAX_WORD_LEN = 7;
const int MAX_DIGIT_COUNT_LEN = 4;
const bool LOCAL_DEBUG_FLAG = false;
int main()
{
DEBUG = LOCAL_DEBUG_FLAG;
int i;
char output[MAX_STRING_LEN];
char intVal[MAX_DIGIT_COUNT_LEN];
printDebug("Initial Loop Start\n");
for (i = 1; i <= 100; i++)
{
printDebug("Setting initial output to null\n\n");
/* Set first value in array to null termination,
* effectively clearing the array,
* if it is only read as a sequential string */
output[0] = '\0';
snprintf(intVal, MAX_DIGIT_COUNT_LEN,"%d",i);
evaluate(output, 3, i, "Fizz");
evaluate(output, 4, i, "Buzz");
evaluate(output, 5, i, "Sizzle");
output[sizeof(output)] = '\0';
if (output[0] == '\0')
{
strncat(output, intVal, MAX_DIGIT_COUNT_LEN);
}
printf("%s\n", output);
}
}
void evaluate(char *buf, int factor, int value, char *result)
{
printDebug("Evaluating || Factor: %d, Value: %d, Success Result: %s\n", factor, value, result);
char temp[MAX_WORD_LEN];
strncpy(temp, ((value % factor == 0) ? result : ""), MAX_WORD_LEN -1);
printDebug("Evaluating complete || Result: \"%s\"\n\n", temp);
//Check array is not empty
if (value % factor == 0)
{
strncat(buf, temp, MAX_STRING_LEN -1);
}
}
Debug Util Header
#ifndef C_EXAMPLES_DEBUG_UTIL_H
#define C_EXAMPLES_DEBUG_UTIL_H
#ifndef _STDIO_H_
#include <stdio.h>
#endif
#include <zconf.h>
#ifndef _STDBOOL_H
#include <stdbool.h>
#endif
extern bool DEBUG;
#endif //C_EXAMPLES_DEBUG_UTIL_H
Debug Util C Source
#include "debug_util.h"
bool DEBUG = false;
//Only prints if the global DEBUG flag has been set to true
//Replicates code from printf()
int printDebug(const char *format, ...)
{
int done = 0;
if (DEBUG)
{
va_list arg;
va_start (arg, format);
done = vfprintf (stdout, format, arg);
va_end (arg);
}
return done;
}