1

我在使用该strtok()功能时遇到问题。我喂这个日期01/01/2000; 我的预期输出是:1、1、2000;但是我只是得到 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;
}
4

2 回答 2

3

首先,您要使用strtol代替atoi(或sscanf,见下文)。该功能atoi不安全。

其次,strtok需要NULL而不是string

pointerToDateStructure->day = atoi(strtok( string, delim));
pointerToDateStructure->month = atoi(strtok( NULL, delim)); /* NULL instead of string. */
pointerToDateStructure->year = atoi(strtok( NULL, delim)); /* See above. */

第三,您没有检查strtok.

作为旁注,您确定sscanf无法解析您的数据吗?

sscanf(str, "%d/%d/%d", &day, &month, &year)

abelenky编辑解释:

函数 strtok 有状态。它“记住”它之前正在处理的字符串,如果你传递“NULL”,它会继续处理同一个字符串,从之前停止的地方开始。如果每次都传递一个字符串参数,则每次都从开头开始。

于 2011-10-19T14:59:43.847 回答
0

sscanf(str, "%02d/%02d/%[^\n], &day, &month, &year)是最简单的选项之一,但您应该准确使用格式;否则一切都会出错。

如果你真的想使用strtok(),就按照 cnicutar 说的方式使用它,但是每一步都要精确验证。

于 2011-10-19T15:23:01.107 回答