簡體   English   中英

使用 strtok 驗證用戶在 C 中輸入的日期的問題

[英]Issue using strtok to validate a user-entered date in C

我試圖在 C 中驗證用戶輸入的日期。但是,我似乎無法讓 strtok 由“-”分隔符分隔。 例如,我想驗證用戶是否以 mm/dd/yyyy-hh:mm 格式正確輸入了日期,其中 hh 是小時的 2 位數字表示,而 mm 也是 2 位數字小時后的分鍾數。

這就是我一直在做的。

 char* input[] //--user input

 char* token[];//-- used to seperate each portion and verify them individually.

 token = strtok(input, " /-:"); //-- token is now the mm.
 ...todo

token = strtok(NULL, "/"); //---token is now the dd.
...todo

token = strtok(NULL, "/"); //---token is now the yyyy.
...todo

我一直在每一步都使用 prinf 令牌進行驗證,一切都運行順利,直到我嘗試到達 hh。

這是問題:當我嘗試打電話時

token = strtok(NULL, "-") //for the hours in a valid input

令牌為 NULL。 在 todo 中,我驗證令牌不為空,但在這種情況下,即使我輸入有效日期,它也始終為空。

你可以考慮使用

if ( sscanf ( input, "%d/%d/%d-%d:%d", &mm, &dd, &yyyy, &hr, &m) == 5)

格式字符串掃描一個 int、一個'/' 、一個 int、一個'/' 、一個 int、一個'-' 、一個 int、一個':'和一個 int。 如果成功掃描所有項目,則返回 5。

暫無
暫無

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

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