CLIから日付を取得しようとしています。ただし、std::cin >> を int で直接使用しているときに文字列など、無効な値を入力するとプログラムが誤動作するため、最初は文字列として取得しています。これまでの私のコードは、期待どおりに動作していません。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;
}