[英]Trying to break out of a string loop
好的,所以我一直在解決我在下面的“過程”function 中遇到的問題。 當我提交我的代碼時,我得到了正確的 output 但我的循環永遠不會結束。 當我嘗試結束循環時,我沒有得到 output。 如果變量是 integer,我知道如何結束循環,但字符串讓我陷入循環。 我是新手,我確信解決方案可能就在我面前。 謝謝您的幫助。
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;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.