c - 如何将数据存储在 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'
解决方案
如果你想用字符串来做:
#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;
}
推荐阅读
- javascript - 从laravel控制器返回json时尝试获取非对象的属性“id”
- java - 通过克隆在java中进行深度复制
- c - 是否有任何工具可以发现 C 源代码中的潜在错误?
- python - 试图交换列表中的位置
- android - 冲突的房间数据库不工作,数据总是被插入
- python - 根据 Python 中的变量更改值
- c# - 使用异常分割 SQL 脚本
- python - builtins.AttributeError AttributeError:模块'csv'没有属性'Dictwriter'
- python - Python BeautifulSoup 解析脚本标签
- ios - CATextLayer 无法在 SCNNode 上正确渲染