在 C 中使用 strtok 将日期字符串转换为整数
我在使用 strtok()
函数时遇到问题。我输入的日期为 01/01/2000
;我的 预期产出为:2000 年 1 月 1 日;但我只得到 1, 1, 1。 这是为什么?
#include <stdio.h>
#include <stdlib.h>
#include "date.h"
#include <string.h>
struct date{
int day;
int month;
int year;
};
Date *date_create(char *datestr){
printf("inside date_create");
char delim[] = "/";
Date* pointerToDateStructure = malloc(sizeof(Date));
printf("%s",datestr);
char string[10];
*strcpy(string, datestr);
pointerToDateStructure->day = atoi(strtok( string, delim));
pointerToDateStructure->month = atoi(strtok( string, delim));
pointerToDateStructure->year = atoi(strtok( string, delim));
printf("%d", pointerToDateStructure->day);
printf("%d", pointerToDateStructure->month);
printf("%d", pointerToDateStructure->year);
return pointerToDateStructure;
}
I'm having trouble using the strtok()
function. I feed this a date of 01/01/2000
; my
expected output is: 1, 1, 2000; however I'm just getting 1, 1, 1.
Why is that?
#include <stdio.h>
#include <stdlib.h>
#include "date.h"
#include <string.h>
struct date{
int day;
int month;
int year;
};
Date *date_create(char *datestr){
printf("inside date_create");
char delim[] = "/";
Date* pointerToDateStructure = malloc(sizeof(Date));
printf("%s",datestr);
char string[10];
*strcpy(string, datestr);
pointerToDateStructure->day = atoi(strtok( string, delim));
pointerToDateStructure->month = atoi(strtok( string, delim));
pointerToDateStructure->year = atoi(strtok( string, delim));
printf("%d", pointerToDateStructure->day);
printf("%d", pointerToDateStructure->month);
printf("%d", pointerToDateStructure->year);
return pointerToDateStructure;
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
首先,您要使用
strtol
而不是atoi
(或sscanf
,见下文)。函数atoi
是不安全的。其次,
strtok
需要NULL
而不是string
:第三,您没有检查
strtok
返回的值。附带说明一下,您确定 sscanf 无法解析您的数据吗?
编辑 abelenky 的解释:
函数 strtok 有状态。它“记住”它之前正在处理的字符串,如果您传递“NULL”,它会继续处理同一个字符串,从之前停止的地方开始。如果每次传递一个字符串参数,则每次都会从头开始。
First of all, you want to use
strtol
instead ofatoi
(orsscanf
, see below). The functionatoi
is unsafe.Second,
strtok
needsNULL
instead ofstring
:Third, you are not checking the value returned by
strtok
.As a side note, are you sure
sscanf
can't parse your data ?EDIT Explanation by abelenky:
The function strtok has state. It "remembers" what string it was working on before, and if you pass "NULL", it continues to work on that same string, picking up where it stopped before. If you pass it a string parameter each time, it starts at the beginning each time.
sscanf(str, "%02d/%02d/%[^\n], &day, &month, &year)
是最简单的选项之一,但你应该精确与格式;否则一切都会出错。如果您确实想使用 strtok(),请按照 cnicutar 所说的方式使用它,但每一步都要进行精确的验证。
sscanf(str, "%02d/%02d/%[^\n], &day, &month, &year)
is the one of the easiest options, but you should be precise with the format; otherwise everything will go wrong.If you really want to use
strtok()
, use it in the exact way as cnicutar said but be precise with verification at each step.