簡體   English   中英

在C中使用strtok將日期字符串轉換為int

[英]Using strtok in C to convert a date string to ints

我在使用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;
}

首先,你想使用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”,它將繼續在該字符串上工作,並選擇之前停止的位置。 如果您每次都給它傳遞一個字符串參數,則它每次都會從開頭開始。

sscanf(str, "%02d/%02d/%[^\\n], &day, &month, &year)是最簡單的選項之一,但您應該精確地使用格式;否則一切都會出錯。

如果你真的想使用strtok() ,請像cnicutar所說的那樣使用它,但在每一步都要精確驗證。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM