2014-11-23 66 views
0

在C++我正在創建一個程序,要求用戶輸入以下格式的日期:MM/DD/YYYY。由於日期是一個int,並且必須是一個int,所以我認爲最合理的方法是將數組放在一行中。有沒有辦法在獲取數組的用戶輸入時忽略char?

所以我創造了這樣的事情......

int dateArray[3]; 
for (int i=0; i<3; i++) 
    cin >> dateArray[i]; 
int month = dateArray[0]; 
...etc 

我的問題是,如果用戶輸入「1980年1月23日」有什麼辦法,我可以忽略/用戶輸入?

謝謝。

+1

[的std :: istream的::忽略()](http://en.cppreference.com/w/cpp/io/basic_istream/ignore) – 2014-11-23 19:08:50

+0

我會怎麼用它在這一範圍內,雖然? – 2014-11-23 19:09:43

+0

鏈接的引用中給出的示例沒有幫助嗎?只需使用「/」而不是「\ n」和只有數字輸入。 – 2014-11-23 19:11:32

回答

2

您可以使用std::istream::ignore()忽略一個字符。由於您可能只想忽略中間字符,因此您需要知道何時忽略以及何時不忽略。約會我個人並不理會,但剛讀了三個詞:

if (((std::cin >> month).ignore() >> year).ignore() >> day) { 
    // do something with the date 
} 
else { 
    // deal with input errors 
} 

我實際上也傾向於檢查正確的分離器接收並可能只是營造操縱爲了這個目的:

std::istream& slash(std::istream& in) { 
    if ((in >> std::ws).peek() != '/') { 
     in.setstate(std::ios_base::failbit); 
    } 
    else { 
     in.ignore(); 
    } 
    return in; 
} 

// .... 
if (std::cin >> month >> slash >> year >> slash >> day) { 
    // ... 
} 

...顯然,我會檢查所有情況下輸入是正確的。

0

我不會理睬它;它是你的格式的一部分,即使你不需要無限期地保留它。

我會將它讀入char並確保它實際上是/

1

考慮使用C++ 11正則表達式庫支持這種類型的解析。例如

#include <iostream> 
#include <iterator> 
#include <regex> 
#include <string> 


int main() 
{ 
    std::string string{ "12/34/5678" }; 
    std::regex regex{ R"((\d{2})/(\d{2})/(\d{4}))" }; 

    auto regexIterator = std::sregex_iterator(std::begin(string), std::end(string), regex); 

    std::vector<std::string> mdy; 
    for(auto matchItor = regexIterator; matchItor != std::sregex_iterator{}; ++matchItor) 
    { 
    std::smatch match{ *matchItor }; 
    mdy.push_back(match.str()); 
    } 

    const std::size_t mdySize{ mdy.size() }; 
    for(std::size_t matchIndex{ 0 }; matchIndex < mdySize; ++matchIndex) 
    { 
    if(matchIndex != mdySize && matchIndex != 0) std::cout << '/'; 
    std::cout << mdy.at(matchIndex); 
    } 
} 
相關問題