0

我正在尝试从 CLI 获取日期。但是,我首先将它作为字符串获取,因为当我输入一些无效值时程序行为异常,例如,直接在 int 上使用 std::cin >> 时的字符串。到目前为止,这是我的代码,它的行为不符合预期。以 mm/dd/yyyy 格式输入日期后,仍然显示“我们无法解释您的输入”。下面是我的代码,任何帮助将不胜感激:

  while (true)
{
      bool success = true;
      std::cout << "Enter the date added to inventory in the format mm/dd/yyyy: ";
      std::string mm, dd, yyyy;
      std::string temp;
      std::getline(std::cin,temp);
      for (int i=0; i<temp.size(); i++)
        {
          if ((temp[i]=='/') || (temp[i]='\\') || (temp[i] == '-'))
              temp[i] = ' ';
        }
      std::stringstream datestream(temp);
      datestream >> mm >> dd >> yyyy;
      try {
      date->month = static_cast<char>(std::stoi(mm.c_str()));
      date->day = static_cast<char>(std::stoi(dd.c_str()));
      date->year = static_cast<int>(std::stoi(yyyy.c_str()));
      } catch (std::invalid_argument e)
        {
          std::cout << "We could not interpret your input. \n";
          success = false;
        } catch (std::out_of_range e)
        {
          std::cout << "Your input was too large. Please try a smaller number a smaller number for dd, mm, and yyyy. \n";
          success = false;
        }
      if (success)
        break;
}
4

1 回答 1

1

在您的 if 条件下,您在第 10 行将 // 分配给临时索引 i。第 11 行也将空格分配给临时索引 i。我确信这只是一个“错字”,但在编程中,双等号是比较器运算符,而一个等号是分配运算符。

于 2021-02-02T03:38:02.727 回答