试图打破一个字符串循环

好的,所以我一直在解决以下“过程”功能的问题。提交代码时,我得到正确的输出,但循环永无休止。当我尝试结束循环时,没有任何输出。我知道如果变量是一个整数但该字符串使我陷入循环,如何结束循环。我对此并不陌生,我敢肯定解决方案可能就在我的面前。感谢您的帮助。

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();
}
zhaiyawei88 回答:试图打破一个字符串循环

尝试将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;
}
本文链接:https://www.f2er.com/3120244.html

大家都在问