有没有办法在获取数组的用户输入时忽略字符

Is there a way to ignore a char when getting user input for array?

本文关键字:输入 字符 用户 获取 数组 有没有      更新时间:2023-10-16

in C++ 我正在创建一个程序,要求用户输入以下格式的日期:月/日/年。由于日期是一个 int 并且必须是 int,我认为在一行中获取它的最合乎逻辑的方法是如果我要使用数组。

所以我创造了这样的东西...

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

我的问题是,如果用户输入"1/23/1980",有没有办法忽略用户输入的/?

谢谢。

您可以使用

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) {
    // ...
}

。而且,显然,我会在所有情况下检查输入是否正确。

考虑对这种类型的解析使用 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 );
  }
}

我不会忽略它;它是你格式的一部分,即使你不需要无限期地保留它。

我会把它读成char,并确保它实际上是/.