【发布时间】:2020-11-21 07:48:11
【问题描述】:
除了在cout<<"From Date: "; 之后到达getline() 之外,此程序中的一切都运行良好。在这一点上,无论我是输入还是直接按Enter而不输入,我都必须按两次Enter才能继续。我尝试删除cin.ignore(),但跳过第一个getline() 会导致更多问题。这是导致此问题的 sn-p-
int main() {
Date d1;
int choice;
cout << "\nEnter choice: ";
cin >> choice;
cin.ignore(numeric_limits < streamsize > ::max(), '\n');
switch (choice) {
case 1:
d1.diffbw();
break;
default:
cout << "Wrong choice";
}
return 0;
}
void Date::diffbw() {
Date current, ref;
string choice;
cout << "\n Type 'man' to enter date manually else hit Enter to insert current date!";
do {
cout << "From Date:";
getline(cin, choice);
if (choice == "man")
current.getdate(); //getdate() assigns day, month and year in object current
else if (choice.empty())
current = sysDate(); //sysDate returns system date
else {
cout << "\n Wrong Choice!";
cout << "\n Enter Again?(y/n): ";
getline(cin, choice);
}
} while (choice == "y" || choice == "Y");
do {
cout << "To Date:";
getline(cin, choice);
if (choice.empty())
ref = sysDate();
else if (choice == "man")
ref.getdate();
else {
cout << "\n Wrong Choice!";
cout << "\n Enter Again?(y/n): ";
getline(cin, choice);
}
} while (choice == "y" || choice == "Y");
current.calcAge(ref); //calcAge() calculates difference between two given dates.
cout << "\n Difference: ";
cout << abs(current.day) << " day(s) " << abs(current.month) << " month(s) " << abs(current.year) << " year(s)";
}
P.S.- 我在 windows 上使用 g++ 编译器。
编辑:我在这里发布了整个函数,因为很多人难以理解这里的上下文。我还按照@john 的建议更正了“cin.ignore()”语法。我正在尝试计算两个给定日期之间的差异。
第二个“do while”循环没有任何错误,尽管它与第一个完全同义。
【问题讨论】:
-
您错误地使用了
cin.ignore。当您知道有要丢弃的输入时,应在 输入之后使用 ignore。当您无法知道输入流的状态时,不应在输入之前使用它。。 -
如果你使用Linux,你可以考虑使用GNU readline。然后输入行是可编辑的。否则,当您的程序在某个 pipeline 中时会发生什么?
-
尝试在
cout行的末尾添加<< std::flush。 -
阅读getline
-
请提供minimal reproducible example,这段代码之前你在做什么?