2012-02-14 3 views
-1

날짜 유효성 검사를 위해이 코드를 작성했습니다. 정상적으로 작동하지만 문자열을 보내야하며이 함수에 들어가 문자열을 검증하고 다시 반환해야합니다. 내가 코드를 변경하는 방법을 ...C 코드를 변경해야합니다.

는 내가 ..이 내입니다

main() 
{ 

dobvalidation(b); 

} 

void dobvalidation(string b) 
{ 
//validates 
} 

내가 위의 형식으로해야합니다 .. 정적 제거하고 난 전직에 대한 원하는 출력 ..를 받고 있지 않다 프로토 타입 변수를 사용하는 경우 코드

매우 높은 수준에서
#include <iostream> 
#include <string> 
#include <cstring> 
#include <stdlib.h> 
#include <ctime> 
using namespace std; 
void checkFormat(); 
void dobValidation(); 
static string input; 
int main() 
{ 
    cout<<"Enter date of birth (dd-mm-yyyy)\n"; 
    getline(cin,input,'\n'); 
    checkFormat(); 
dobValidation(); 
    return 0; 
} 

void checkFormat() 
{ 

    //check the length of the string 
    int len=input.size(); 
    if(len!=10) 
    { 
     cout<<"\nPlease enter a valid Date of Birth\n"; 
     cin>>input; 
     checkFormat(); 
     return; 
    } 

    char * val; 
    val = const_cast<char*>((input.substr(2,1)).c_str()); 

    //check for the dashes in dob 
    if(strcmp(val,"-")!=0) 
    { 
     cout<<"\nPlease enter a valid Date of Birth\n"; 
     cin>>input; 
     checkFormat(); 
     return; 
    } 

     val = const_cast<char*>((input.substr(5,1)).c_str()); 

    if(strcmp(val,"-")!=0) 
    { 
     cout<<"\nPlease enter a valid Date of Birth\n"; 
     cin>>input; 
     checkFormat();  
     return; 
    } 

    //check for digits 

    //extract date from string 

    char * date; 
    date = const_cast<char*>((input.substr(0,2)).c_str()); 
    //check char by char for numeric 
    char c; 
    for(int i=0;i<2;i++) 
    { 
     c = date[i]; 
     if(!isdigit(c)) 
     { 
      cout<<"\nPlease enter a valid Date of Birth\n"; 
      cin>>input; 
      checkFormat(); 
      return; 
     } 

    } 

    //extract month from string 

    char * month; 
    month = const_cast<char*>((input.substr(3,2)).c_str()); 

    //check char by char for numeric  
    for(int i=0;i<2;i++) 
    { 
     c = month[i]; 
     if(!isdigit(c)) 
     { 
      cout<<c; 
      cout<<"\nPlease enter a valid Date of Birth\n"; 
      cin>>input; 
      checkFormat(); 
      return; 
     } 

    } 

    //extract year from string 
    char * year; 
    year = const_cast<char*>((input.substr(6,4)).c_str()); 

    //check char by char for numeric  
    for(int i=0;i<4;i++) 
    { 
     c = year[i]; 
     if(!isdigit(c)) 
     { 
      cout<<"\nPlease enter a valid Date of Birth\n"; 
      cin>>input; 
      checkFormat(); 
      return; 
     } 

    } 
return; 
} 



void dobValidation() 
{ 
//  cout<<dob; 
    //date 
     char * date1; 
     date1 = const_cast<char*>((input.substr(0,2)).c_str()); 
     int dd=atoi(date1); 

     //month 
     char * month1; 
     month1 = const_cast<char*>((input.substr(3,2)).c_str()); 
     int mm=atoi(month1); 

     //year 
     char * year1; 
     year1 = const_cast<char*>((input.substr(6,4)).c_str()); 
     int yyyy=atoi(year1); 

    //cout<<dd<<mm<<yyyy; 
     int days[12]={31,28,31,30,31,30,31,31,30,31,30,31}; 

     int max_no_of_day = days[mm-1]; 

     //check for leap year 

     if((yyyy%400 ==0 || (yyyy%100 != 0 && yyyy%4 == 0)) && mm==1) 
     { 
         max_no_of_day=29; 
     } 
     // check date doesnt cross the max limit 
     if(dd > max_no_of_day || dd<1) 
     { 
    // cout<<"max"<<max_no_of_day<<endl; 
    // cout<<dd<<mm<<yyyy; 
       cout<<"\nPlease enter a valid Date of Birth\n"; 
       cin>>input; 
       dobValidation(); 
     return; 
     } 

     // month validation 

     if(mm >12 || mm<1) 
     { 
       cout<<"\nPlease enter a valid Date of Birth\n"; 
       cin>>input; 
       dobValidation(); 
     return; 
     } 
//year verification 

     time_t t = time(0); // get time now 
    struct tm * now = localtime(& t); //convert to local time 
    int current_year = (now->tm_year + 1900); 
    int current_month = (now->tm_mon + 1); 
    int current_date = (now->tm_mday); 


    // date should not exceed current date 
    if(yyyy==current_year && mm>current_month) 
    { 
     cout<<"\nPlease enter a valid Date of Birth\n"; 
       cin>>input; 
       dobValidation(); 
     return; 
    } 

    if(yyyy==current_year && mm==current_month && dd>current_date) 
    { 
     cout<<"\nPlease enter a valid Date of Birth\n"; 
       cin>>input; 
       dobValidation(); 
     return; 
    } 

    //check whether year crossed current year 
    if(yyyy>current_year || yyyy<1900) 
    { 
     cout<<"\nPlease enter a valid Date of Birth\n"; 
       cin>>input; 
       dobValidation(); 
     return; 
    } 


return; 
     } 
+0

const_cast를 사용하지 마십시오. 변수를'char *'에서'const char *'로 바꾼다 – balki

+1

아니면 필요가 없을 때 C- 문자열을 사용하지 말고 캐스트를 피하라. – Duck

답변

4

, 여기에 내가 제안 내용은 다음과 같습니다

  • 글로벌사용하지 마십시오. 입력을 매개 변수로 함수에 전달하십시오.

  • 함수를 재귀 적으로 호출하지 마십시오. 함수에서 성공/실패 결과를 반환하고 주 루프가 수행 할 작업을 결정하도록합니다.

예를 들어, 메인 루프는 다음과 같이 수 : static string input 같은

int main() 
{ 
    while (true) { 
     cout<<"Enter date of birth (dd-mm-yyyy)\n"; 
     string input; 
     getline(cin,input,'\n'); 
     if (!checkFormat(input)) { 
      cout<<"\nPlease enter a valid Date of Birth\n"; 
      continue; 
     } 
     if (!dobValidation(input)) { 
      cout<<"\nPlease enter a valid Date of Birth\n"; 
      continue; 
     } 
     cout << "thanks.\n"; 
     break; 
    } 
} 
+0

예, 이해합니다 .. 시도해 보겠습니다. – srinathmkce

0

일반적으로, 전역 변수는 좋은 코딩 연습을하지 않습니다. 나는 이런 식으로 할 것입니다 :

main() { 
    string input; 
    bool isValid = false; 

    cout<<"Enter date of birth (dd-mm-yyyy)\n"; 
    getline(cin,input,'\n'); 

    while(!checkFormat(input) || !dobValidation(input)) { 
     cout<<"Please enter a valid date of birth (dd-mm-yyyy)\n"; 
     getline(cin,input,'\n');   
    } 
    return 0; 
} 

bool checkFormat(string input) { 
    // return true if format is valid, false otherwise 
} 

bool dobValidation(string input) { 
    // return true if dob is valid, false otherwise 
} 
0

낮은 수준에서 당신은 C++을 고수함으로써 많은 것을 단순화 할 수 있습니다.

같은 예를 들어 것들에 대한
//extract year from string 
char * year; 

year = const_cast<char*>((input.substr(6, 4)).c_str()); 

//check char by char for numeric 
for (int i = 0;i < 4;i++) 
{ 
    c = year[i]; 

    if (!isdigit(c)) 
    { 
     cout << "\nPlease enter a valid Date of Birth\n"; 
     cin >> input; 
     checkFormat(); 
     return ; 
    } 

} 

그렉는 당신에게 최고 수준의 준

//check year for numerics 
for (int i = 6; i < 10; i++) 
{ 
    if (! isdigit(input[i])) 
    { 
     return false; 
    } 
} 
0

이 될 수있다, 그래서 용기에 대한 올바른 방향으로 당신을 가리킬 수 있습니다 : strptime.

이것은 Windows 용 지원에 관심이 있다면 아마도 동등한 유틸리티 일 것입니다.

사용 된 형식 문자열은 자매 인 strftime의 형식 문자열과 비슷하며 consulted here이 될 수 있습니다. 귀하의 경우에는

:

bool checkFormat(std::string const& str, tm& date) { 
    char const* const s = strptime(str.c_str(), "%d-%m-%Y", &date); 
    return s != NULL; // NULL indicates failure 
} 

참고이 (문서화) 단점이 있다는 것을 :

tm.tm_year // number of years since 1900 
tm.tm_mon // month in [0..11] (where 0 is January and 11 is December) 

정확한 표현에 대한 자세한 내용은 struct tm 문서를 읽기.

관련 문제