Using std::stringstream to obtain date

198 Views Asked by At

I am trying to obtain the date from CLI. However, I am first getting it as a string because the program misbehaves when I input in some invalid value e.g., a string while using std::cin >> directly on an int. Here is my code so far and it is not behaving as expected. After entering in the date in mm/dd/yyyy format, it still shows "We could not interpret your input". Here is my code below, any help would be greatly appreciated:

  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;
}
1

There are 1 best solutions below

1
On

In your if condition, you are assigning // to temp index i on line 10. A white space is also being assigned on the 11th line to temp index i. I am sure this was just a "typo" but in programming the double equals sign is a comparator operator while one equal sign is an assigning operator.