首页 > 解决方案 > 如何将数据存储在 char 数组中并在 C 中转换为 int

问题描述

因此,我目前将文件指针作为参数,因为我正在读取存储在文件中的数据,14 00 05其中14小时00是分钟,05秒是秒。我希望能够将这些值转换为单个 int 并产生输出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);
}

我目前遇到的问题是,当我读入char mins[2]存储在其中的第一个字符时,char hrs[2]由于某些未知原因而变得 ovverun。之后的输出示例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'

标签: c

解决方案


如果你想用字符串来做:

#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;
}

推荐阅读