【发布时间】:2021-02-02 02:58:12
【问题描述】:
我正在尝试从 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;
}
【问题讨论】:
-
你的错误在这里:
(temp[i]='\\')这是一个分配而不是比较。我最初没有看到这一点,但在这里用一个简单的 std::cout 发现了这一点:https://ideone.com/eTz6ld -
非常感谢。我永远不会自己抓住它。
-
附带说明,如果您描述的是输入问题,并且您说您输入了“日期”,那么它实际上并没有那么有帮助或描述性。 “日期”可以是任何东西。练习简洁。例如,您可以改为提供您输入的确切日期。
-
我的建议是使用 cout,就像我在 ideone.com 链接中所做的那样,或者了解如何使用调试器。如果你成为一名专业的程序员,最终你将需要知道如何很好地调试。
-
感谢您的建议。我应该提到我的确切意见。 cout 声明是个好主意。即使是我认为微不足道和容易的事情,交叉检查总是一件好事。最终,随着我的经验越来越丰富,我希望在调试时学会质疑每一件小事。我真的应该练习使用调试器。非常感谢您的建议。
标签: c++ console-application cin stringstream invalidargumentexception