2014-09-30 7 views
0

간단한 날짜 (mm/dd/yyyy)를 긴 날짜 (2014 년 3 월 12 일)로 변환하고 날짜를 인쇄하는 프로그램을 작성 중입니다. 2014년 10월 23일 2014년 9월 25일 2015년 12월 8일 2016년 1월 1일문자열에서 문자를 검색하려면 어떻게해야합니까?

내가 작업 프로그램이 있습니다

프로그램은 다음과 같은 사용자 입력 주어진 일해야 첫 번째 사용자 입력하지만 문자열의 첫 번째 위치에 "0"이없는 사용자 입력을 처리하는 방법을 잘 모르겠습니다.

#include <iostream> 
#include <string> 

using namespace std; 

int main() 
{ 
    string date; 
    cout << "Enter a date (mm/dd/yyyy): " << endl; 
    getline(cin, date); 

    string month, day, year; 

    // Extract month, day, and year from date 
    month = date.substr(0, 2); 
    day = date.substr(3, 2); 
    year = date.substr(6, 4); 

    // Check what month it is 
    if (month == "01") { 
     month = "January"; 
    } 
    else if (month == "02") { 
     month = "February"; 
    } 
    else if (month == "03") { 
     month = "March"; 
    } 
    else if (month == "04") { 
     month = "April"; 
    } 
    else if (month == "05") { 
     month = "May"; 
    } 
    else if (month == "06") { 
     month = "June"; 
    } 
    else if (month == "07") { 
     month = "July"; 
    } 
    else if (month == "08") { 
     month = "August"; 
    } 
    else if (month == "09") { 
     month = "September"; 
    } 
    else if (month == "10") { 
     month = "October"; 
    } 
    else if (month == "11") { 
     month = "November"; 
    } 
    else { 
     month = "December"; 
    } 

    // Print the date 
    cout << month << " " << day << "," << year << endl; 
    return 0; 
} 

대단히 감사하겠습니다.

+4

을 대신 미리 정해진 인덱스에 문자열을 얻는. '/'인덱스를 찾아 거기에서 자른다. –

+0

find 멤버 함수를 사용하고 싶습니다. date.find ("/", 0)와 같이/문자를 찾고 위치 0에서 검색 할 수 있습니다. 나는 여전히 월, 일, 년을 파싱해야합니까? 날짜? – JimT

+1

@JimT ['find'] (http://en.cppreference.com/w/cpp/string/basic_string/find)는 고정 값 대신에'date.substr' 호출에서 사용할 오프셋을 제공합니다. – zakinster

답변

2

빨간 독사가 의견에 썼습니다 : /을 검색하면 std::string::find을 사용합니다.

#include <iostream> 

int main() 
{ 
    std::string date = "09/28/1983"; 

    int startIndex = 0; 
    int endIndex = date.find('/'); 
    std::string month = date.substr(startIndex, endIndex); 

    startIndex = endIndex + 1; 
    endIndex = date.find('/', endIndex + 1); 
    std::string day = date.substr(startIndex, endIndex - startIndex); 

    std::string year = date.substr(endIndex + 1, 4); 

    std::cout << month.c_str() << " " << day.c_str() << "," << year.c_str() << std::endl; 

    return 0; 
} 
0

또한 덜 효율적이지만 간단한 솔루션을, 스트림 변환을 이용할 수 :

#include <iostream> 
#include <string> 
using namespace std; 

int main() { 

    string months[] = {"", "January", "February", "Mars", "April", "May", "June", "Jully", "August", "September", "October", "December"}; 

    cout << "Enter a date (mm/dd/yyyy): " << endl; 
    char c; 
    int day, month, year; 
    cin >> day >> c >> month >> c >> year; 
    // error handling is left as an exercice to the reader. 
    cout << months[month] << " " << day << ", " << year << endl; 
    return 0; 
} 
관련 문제