试图突破字符串循环
Trying to break out of a string loop
好的,我一直在排除下面"进程"函数的一个问题。当我提交代码时,我得到了正确的输出,但我的循环永远不会结束。当我试图结束循环时,我没有得到任何输出。如果变量是整数,但字符串正在引发循环,我知道如何结束循环。我是新手,我相信解决方案可能就在我面前。谢谢你的帮助。
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;
}
相关文章:
- 在循环C++中指定字符串之后,不会打印该字符串
- 在while循环中输入带有std::cin的字符串后,控制台会输出大量胡言乱语
- 在for循环中使用auto vs decltype(vec.size())来处理字符串的向量
- C++-字符串是否包含一个带有简单循环的单词
- 在 c++ 中查找字符串中没有循环的数字总和
- 比较两个字符串后卡在无限循环中
- C++ - 使用基于范围的 for 循环将字符值分配给向量中的字符串不会分配值
- 而循环跳过 cin.getline() 对于 C 字符串
- 我正在尝试使用 while 循环从字符串中删除字母,直到没有字母。我在这里做错了什么?
- 如何使用将字符串拆分为 for 循环中的变量的程序
- 是否有可能实现O(N)时间和O(1)空间解决方案,以实现C++中的字符串循环移位
- 循环访问还包含未使用元素的字符串数组
- 循环访问资源字符串表
- C++ - 使用用户输入的字符串数据检查结构字符串数据(无限执行 while 循环)
- 修改向量中的字符串?(不使用循环)
- For 循环字符串忽略字符
- 如何按空格循环字符串?我怎么知道字符串中我当前所在的单词的索引号
- 在 c++ 中循环字符串读取器
- 如何在 c++ 中循环字符串
- 分段错误,通过std按字符循环字符串