Created
December 9, 2018 12:24
-
-
Save Naravia/1d22cbf067c6b120060c74770ab7eaf1 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <stdio.h> | |
enum MODES | |
{ | |
ADDING, | |
SUBTRACTING | |
}; | |
int map_character_to_int(int character) | |
{ | |
switch (character) | |
{ | |
case '0': | |
return 0; | |
case '1': | |
return 1; | |
case '2': | |
return 2; | |
case '3': | |
return 3; | |
case '4': | |
return 4; | |
case '5': | |
return 5; | |
case '6': | |
return 6; | |
case '7': | |
return 7; | |
case '8': | |
return 8; | |
case '9': | |
return 9; | |
default: | |
return -1; | |
} | |
} | |
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; | |
while ((character = fgetc(fp)) != EOF) | |
{ | |
if (character == '+') | |
{ | |
mode = ADDING; | |
continue; | |
} | |
if (character == '-') | |
{ | |
mode = SUBTRACTING; | |
continue; | |
} | |
if (character == '\n') | |
{ | |
if (mode == SUBTRACTING) | |
{ | |
current_value *= -1; | |
} | |
total += current_value; | |
current_value = 0; | |
continue; | |
} | |
int character_value = map_character_to_int(character); | |
if (character_value != -1) | |
{ | |
current_value *= 10; | |
current_value += character_value; | |
continue; | |
} | |
} | |
if (current_value != 0) | |
{ | |
if (mode == SUBTRACTING) | |
{ | |
current_value *= -1; | |
} | |
total += current_value; | |
current_value = 0; | |
} | |
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