2012-11-20 34 views
-1

我必須編寫2個函數。將日期作爲字符串並檢查其是否以mm/dd/yy格式顯示;如果它的格式不正確,則應該對其進行編輯。另一個函數應該將驗證日期轉換爲「Month dd,20yy」的格式。C++中的日期驗證和轉換

我很確定我可以照顧第二個功能,但我遇到了第一個問題。我只是不知道如何檢查其格式是否有任何想法?

我認爲這會工作,但它似乎沒有...

更新代碼:

bool dateValidation(string shipDate) 
{ 
    string temp; 
    if(shipDate.length() == 8) 
    { 
     if(shipDate[2] == '/' && shipDate[5] =='/') 
     { 
      int tempDay, tempMonth, tempYear; 
      //Gather month 
      temp = shipDate[0]; 
      temp += shipDate[1]; 
      //convert string to int 
      tempMonth = temp.atoi; 
      temp = ""; 

      //Gather day 
      temp = shipDate[3]; 
      temp += shipDate[4]; 
      //convert string to int 
      tempDay = temp.atoi; 
      temp = ""; 

      //Gather year 
      temp = shipDate[6]; 
      temp += shipDate[7]; 
      //convert string to int 
      tempYear = temp.atoi; 
      temp = ""; 

      if(tempMonth > 0 && tempMonth <= 12) 
      { 

       if(tempMonth == 9 || 
        tempMonth == 4 || 
        tempMonth == 6 || 
        tempMonth == 11 ||) 
       { 
        if(tempDay > 0 && tempDay <= 30) 
        { 
         if 30 days 
          } 
       } 
       else if(tempMonth == 2) 
       { 
        if(tempDay > 0 && tempDay <= 28) 
        { 
         if 28 days 
          } 
       } 
       else 
       { 
        if(tempDay > 0 && tempDay <= 31) 
        { 
         if 31 days 
          } 
       } 
      } 
     } 
    } 
} 
+0

爲什麼不起作用,是什麼問題?日期還有什麼樣的變化,它可能是這樣的:101112還是它總是在d/m/y之間還有m和d和y可以交換? –

+0

我剛碰到一堵牆。我重複了20次,這是我最後停下的地方。它在這裏不完整。我需要一些幫助來寫它。 :/ –

+0

你實際上沒有驗證這些值是正確的..只是檢查標點符號。 –

回答

0

有要檢查的4件事:

  • 有8個字符嗎?如果不是,那麼甚至不要去檢查其他的東西。它的格式不正確。
  • 是第三個和第五個字符'/'。如果沒有,那麼你仍然沒有適當的格式。
  • 檢查每一對的有效值。一個月的天數最多在1到 之間,最多不超過12個月和月份,範圍從01 到12.一年可以是任意兩位數的任意組合。

這應該照顧的格式,但如果你想確保日期是有效的:

  • 檢查各月(天的有效數字1月31日,二月 28- 29 ...)並確實檢查那些閏年。
+0

我以爲同樣的事情,但有一個問題。技術上1/1/2012是一個有效的日期,但使用這個psuedocode,它不是。我將不得不想出一些方法將「1」變成「01」和「2012」變成「12」。 –

+0

更新了代碼,在正確的軌道上? –

0

這看起來很像我要評分的項目....如果是我要評分的項目,您應該驗證它是否符合格里曆日曆。 2012年1月1日是絕對有效的,儘管如此,你可能想要做什麼,我希望你考慮創建一個switch語句,檢查格式如2012年1月12日和2012年2月10日,因爲這些是有效的。然後從這些日期和年份中解析出月份。然後驗證它們是否在公曆的範圍內。如果它是針對我認爲是的類,那麼您應該考慮將驗證作爲解析函數的單獨函數來編寫。

因此,首先要問日期是否太長,如果不是,是否太短,如果不是哪個版本,那麼將該日期傳遞給驗證函數。這種模塊化將簡化您的代碼並減少指令。

類似

布爾dateValidation(串SHIPDATE) { 串溫度;

switch(shipDate.length()) 
{ 
    case(10): 
     // do what your doing 
     verify(m,d,y); 
     break; 

    case(8): 
     //dealing with single digits 
     // verify 1 and 3 are '/' and the rest are numbers 
     verifiy(m,d,y); 
     break; 

    case(9): 
     //a little more heavy lifting here 
     // but its good thinking for a new programmer 
     verifiy(m,d,y); 
     break; 
    default:  

     //fail message 
     break; 
}