简体   繁体   English

如何将数据存储在 char 数组中并在 C 中转换为 int

[英]How do I store data in char arrays and convert to int in C

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.因此,我目前将文件指针作为参数,因为我正在读取存储为14 00 05的文件中的数据,其中14是小时, 00是分钟, 05是秒。 I want to be able to convert these values to into a single int and produce the output int time = 140005我希望能够将这些值转换为单个 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);
}

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.我目前遇到的问题是,当我在char mins[2]读取时,存储在char hrs[2]的第一个字符由于某种未知原因而被 ovverun。 Example of output after the fprintf() 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;
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM