使用 std::stringstream 获取日期

问题描述

我正在尝试从 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;
}

解决方法

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