2014-11-23 67 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); 
    } 
} 
相关问题