Skip to content

Instantly share code, notes, and snippets.

@Naravia
Last active December 9, 2018 12:32
Show Gist options
  • Save Naravia/5d31a79b5186079de0f774a41e3677a4 to your computer and use it in GitHub Desktop.
Save Naravia/5d31a79b5186079de0f774a41e3677a4 to your computer and use it in GitHub Desktop.
#include <stdio.h>
enum MODES
{
ADDING,
SUBTRACTING
};
int map_character_to_int(int character)
{
int result = character - '0';
if (result < 0 || result > 9)
{
return -1;
}
else
{
return result;
}
}
int main()
{
const char* FILE_PATH = "Advent.txt";
FILE* fp;
int error = fopen_s(&fp, FILE_PATH, "r");
if (fp == NULL)
{
printf("Could not open file %s. Error code %d", FILE_PATH, error);
return 1;
}
int character;
int total = 0;
int current_value = 0;
int mode = ADDING;
for(;;)
{
character = fgetc(fp);
if (character == '+')
{
mode = ADDING;
continue;
}
if (character == '-')
{
mode = SUBTRACTING;
continue;
}
if (character == '\n' || character == EOF)
{
if (mode == SUBTRACTING)
{
current_value *= -1;
}
total += current_value;
current_value = 0;
if (character == EOF)
{
break;
}
continue;
}
int character_value = map_character_to_int(character);
if (character_value != -1)
{
current_value *= 10;
current_value += character_value;
continue;
}
}
fclose(fp);
printf("Total: %d\n", total);
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment