79 lines
1.6 KiB
C
79 lines
1.6 KiB
C
|
#include <ctype.h>
|
||
|
#include <stdint.h>
|
||
|
#include <stdio.h>
|
||
|
#include <stdlib.h>
|
||
|
#include <stdbool.h>
|
||
|
|
||
|
/*
|
||
|
* Each line of the input file contains a string with a mix of letters and digits
|
||
|
* Each line's "calibration value" is a single two digit number, made up of the first and last
|
||
|
* digit found in the string
|
||
|
* Print out the sum of all the calibration values.
|
||
|
*/
|
||
|
|
||
|
char buffer[2048];
|
||
|
|
||
|
void read_line(char* linebuf, FILE* file)
|
||
|
{
|
||
|
char* str = fgets(linebuf, 2048, file);
|
||
|
if (feof(file))
|
||
|
{
|
||
|
return;
|
||
|
}
|
||
|
if (str == NULL)
|
||
|
{
|
||
|
fprintf(stderr, "Fgets error");
|
||
|
linebuf[0] = '\0';
|
||
|
}
|
||
|
}
|
||
|
|
||
|
void extract_digits(char* str, char *first, char *last)
|
||
|
{
|
||
|
char *p,*q,*r;
|
||
|
p = str;
|
||
|
while (*p != '\0' && !isdigit(*p))
|
||
|
p++; // find first digit
|
||
|
*first = *last = *p;
|
||
|
q = p;
|
||
|
while (*q != '\0') // find digits until end of string
|
||
|
{
|
||
|
q++;
|
||
|
if (isdigit(*q))
|
||
|
{
|
||
|
*last = *q;
|
||
|
}
|
||
|
}
|
||
|
}
|
||
|
|
||
|
long convert_chars(char first, char last)
|
||
|
{
|
||
|
char num[3] = { first, last, '\0' };
|
||
|
return strtoul(num, NULL, 10);
|
||
|
}
|
||
|
|
||
|
int main(int argc, char *argv[])
|
||
|
{
|
||
|
FILE* input = fopen("input", "r");
|
||
|
if (input == NULL)
|
||
|
{
|
||
|
fprintf(stderr, "error opening file");
|
||
|
return EXIT_FAILURE;
|
||
|
}
|
||
|
long sum = 0;
|
||
|
char first, last;
|
||
|
|
||
|
while(true)
|
||
|
{
|
||
|
read_line(buffer, input);
|
||
|
if (feof(input))
|
||
|
break;
|
||
|
extract_digits(buffer, &first, &last);
|
||
|
long value = convert_chars(first, last);
|
||
|
printf("%ld\t%s", value, buffer);
|
||
|
sum += value;
|
||
|
}
|
||
|
|
||
|
printf("%ld", sum);
|
||
|
return EXIT_SUCCESS;
|
||
|
}
|