#include // Only works for positive numbers so far! char * snafu(char * dest, size_t len, long n) { size_t i = 0, j; // Build string in reverse. while (n && i < len) { int d = n % 5; switch (d) { case 0: case 1: case 2: dest[i++] = '0' + d; break; case 3: dest[i++] = '='; n += 5; break; case 4: dest[i++] = '-'; n += 5; break; } n /= 5; } dest[i] = '\0'; // Reverse string to be right way around for (j = 0; j < i / 2; ++j) { char tmp = dest[j]; dest[j] = dest[i - 1 - j]; dest[i - 1 - j] = tmp; } return dest; } int main() { long i = 0, total = 0; int c; char buf[BUFSIZ]; while ((c = fgetc(stdin)) != EOF) { switch (c) { case '2': i *= 5; i += 2; break; case '1': i *= 5; i += 1; break; case '0': i *= 5; break; case '-': i *= 5; i -= 1; break; case '=': i *= 5; i -= 2; break; case '\n': #if 0 fprintf(stderr, "%s (%ld)\n", snafu(buf, sizeof(buf), i), i); #endif total += i; i = 0; break; default: fprintf(stderr, "Unexpected input: %c\n", c); return -1; } } printf("Total: %s (%ld)\n", snafu(buf, sizeof(buf), total), total); return 0; }