So I currently take a file pointer as a parameter as im reading data in a file stored as 14 00 05
where 14
is the hours 00
is the minutes and 05
is the seconds. I want to be able to convert these values to into a single int and produce the output int time = 140005
int time_conversion(FILE *file) {
char hrs[2];
char mins[2];
char secs[2];
char total[6];
fscanf(file, " %s %s %s", hrs, mins, secs);
strcat(total, hrs);
strcat(total, mins);
strcat(total, secs);
return atoi(total);
}
The issue I'm currently having is that when I read in the char mins[2]
the first char stored in char hrs[2]
gets ovverun for some unkown reason. Example of output after the fprintf()
char hrs[0] = '\000'
char hrs[1] = '4'
char mins[0] = '\000'
char mins[1] = '0'
char secs[0] = '0'
char secs[1] = '5'
If you want to do it with strings:
#include <stdio.h>
#include <string.h>
#include <stdlib.h>
int time_conversion(FILE* file) {
char hrs[3];
char mins[3];
char secs[3];
char total[7];
fscanf(file, "%s %s %s", hrs, mins, secs);
strcpy(total, hrs);
strcat(total, mins);
strcat(total, secs);
return atoi(total);
}
int main(void) {
FILE* f = fopen("file.txt", "r");
int wynik = time_conversion(f);
printf("%d", wynik);
return 0;
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.