在C ++中我正在创建一个程序,用以下格式询问用户日期:MM / DD / YYYY。由于日期是一个int并且必须是一个int,我认为在一行中得到这个的最合理的方法是使用数组。
所以我创造了这样的东西......
int dateArray[3];
for (int i=0; i<3; i++)
cin >> dateArray[i];
int month = dateArray[0];
...etc
我的问题是,如果用户输入“1/23/1980”,有没有办法可以忽略用户输入的内容?
谢谢。
答案 0 :(得分: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) {
// ...
}
......显然,我会在所有情况下检查输入是否正确。
答案 1 :(得分: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 );
}
}
答案 2 :(得分:0)
我不会忽视它;它是你格式的一部分,即使你不需要无限期地保留它。
我会把它读成char
,并确保它实际上是/
。