我尝试使用我在int main
中的一个函数中询问并修复的do / while循环,以允许整个程序在用户想要的情况下重新运行,但它正在重新运行程序而无需等待用户输入。
int main()
{
int spoolnumber = 0; // Number of spools to be ordered
float subtotalspool = 0; // Spool sub total
float shippingcost = 0; // Shipping cost
float totalcost = 0; // Total cost
char type = 'n';
do {
instruct(); // Print instructions to user
spoolnumber = spoolnum(); // calculate and store number of spools
subtotalspool = stotalspool(spoolnumber); // Calculate subtotal
shippingcost = shipcost(subtotalspool); // Calculate subtotal
totalcost = tcost(subtotalspool, shippingcost); // Calculate final total
// Print final output
results(spoolnumber, subtotalspool, shippingcost, totalcost);
cout << "\n" << " Would you like to run the program again? [y/n]";
}
while (type != 'y');
return 0;
}
答案 0 :(得分:8)
您尚未添加任何代码来接受用户输入。在循环的底部,尝试将cin
中的字符读入type
。
此外,在接受来自cout
的用户输入之前,您可能需要首先刷新cin
的输出。
答案 1 :(得分:8)
您尚未阅读用户的任何输入。你可以这样做:
cin >> type;
但实际上你想要检查它是否也取得了成功,例如如果用户按下 Crtl - D ,那么它仍然可以永远循环,而不是eof或其他错误。
检查是否成功:
if (!(cin >> type)) {
// Reading failed
cerr << "Failed to read input" << endl;
return -1;
}
您实际上可以参与循环条件:
while (cin >> type && type != 'y');
Xeo关于调用cin.ignore()
的建议非常重要,因为您几乎肯定会得到超过char
个输入值。
答案 2 :(得分:6)
嗯,你从不要求输入,是吗?在cout
行之后添加以下内容:
cin >> type;
cin.ignore(); // remove trailing newline token from pressing [Enter]
现在,你仍然需要通常的测试,如果输入有效,等等,但这应该让你去。
答案 3 :(得分:2)
您需要添加cin
才能检索用户的决定:
例如:
cout << "\n" << " Would you like to run the program again? [y/n]";
cin >> someVariable;
答案 4 :(得分:2)
那是因为你没有提示用户输入。
如果尝试以下方式,你会更成功:
cout << "\n" << " Would you like to run the program again? [y/n]";
cin >> type;