【发布时间】:2019-11-12 02:55:40
【问题描述】:
好的,我一直在解决我在下面的“流程”功能中遇到的问题。当我提交我的代码时,我得到了正确的输出,但我的循环永远不会结束。当我尝试结束循环时,我没有得到任何输出。如果变量是整数,我知道如何结束循环,但字符串让我陷入循环。我是新手,我确信解决方案可能就在我面前。感谢您的帮助。
int process()
{
double price = 0;
while(true)
{
int items = 0;
string order = "";
cout << "Enter your order string: ";
cin >> order;
items = findItem(order);
if (items < 0)
{
cout << order << " is invalid. Skipping it.\n";
break;
}
cout << names[items] << ": $" << fixed << setprecision(2) << prices[items] << endl;
price += prices[items];
}
cout << "Total: $" << fixed << setprecision(2) << price;
}
#include <iostream>
#include <iomanip>
#include <fstream>
#include <sstream>
using namespace std;
const int MAXPRODUCTS = 100;
string names[MAXPRODUCTS];
double prices[MAXPRODUCTS];
string codes[MAXPRODUCTS];
int numProducts = 0;
void readConfiguration()
{
int i =0;
ifstream finput("menu.txt");
while(finput >> codes[i] >> names[i] >> prices[i])
{
i++;
numProducts = i;
}
}
//return valid index if the item is found, return -1 otherwise.
int findItem(string inputCode)
{
for(int i =0; i<numProducts; i++)
{
if(inputCode == codes[i])
return i;
}
return -1;
}
// read order string like "A1 A1 E1 E2 S1" and generate the restaurant bill.
// Output the item name and price in each line, total in the final line.
int process()
{
string order = "";
while(true)
{
int items = 0;
cout << "Enter your order string: ";
cin >> order;
items = findItem(order);
if (items < 0)
{
cout << order << " is invalid. Skipping it.\n";
continue;
}
else
cout << names[items] << ": $" << fixed << setprecision(2) << prices[items] << endl;
}
return 0;
}
int main()
{
readConfiguration();
process();
}
【问题讨论】:
-
1) "当我提交代码时,我得到了正确的输出,但我的循环永远不会结束。" 哪个循环? 2) 你的意思是循环
while(true)?你如何“尝试”摆脱它?里面没有break语句,也没有return语句。 -
对不起,我以为我在说“处理函数”时指定了,但是是的,while(true) 循环。目前代码工作它只是永远重复,但如果我试图打破它,它根本不返回任何输出。所以这就是我的困惑。
-
1) 所以,请显示您尝试跳出循环的代码,目前,此代码甚至没有尝试这样做,所以直接的答案是:如果您想要要跳出循环,只需跳出循环.. 2)“但如果我尝试跳出它,它根本不会返回任何输出。”您是否尝试使用单步执行代码一个调试器,想知道为什么会这样?
-
@AlgirdasPreidžius,好的,我编辑了我的原始帖子,并带有循环中断。它位于我帖子的编码部分的顶部。这个问题是当“顺序”错误时它会跳出循环,但它应该跳过它并移动到下一个值。
-
@AlgirdasPreidžius 当没有更多“订单”值需要处理时,我不知道如何结束循环