试图突破字符串循环

Trying to break out of a string loop

本文关键字:循环 字符串 突破      更新时间:2023-10-16

好的,我一直在排除下面"进程"函数的一个问题。当我提交代码时,我得到了正确的输出,但我的循环永远不会结束。当我试图结束循环时,我没有得到任何输出。如果变量是整数,但字符串正在引发循环,我知道如何结束循环。我是新手,我相信解决方案可能就在我面前。谢谢你的帮助。

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();
}

尝试将while(true)编辑为while(cin >> order)

while(cin >> order)
{
int items = 0;
cout << "Enter your order string: ";
items = findItem(order);
if (items < 0)
{
cout << order << " is invalid. Skipping it.n";
continue;
}
else
cout << names[items] << ": $" << fixed << setprecision(2) << prices[items] << endl;
}