简体   繁体   English

如果字符串不等于const char,则退出while循环

[英]If string does not equal const char break out of while loop

I'm having a problem breaking out of this while loop in my code. 我在代码中突破while循环时遇到问题。 If the user is done entering items I want them to press q to exit. 如果用户输入完项目,我希望它们按q退出。 This does not work, q gets entered by the user and the loop is not broken. 这不起作用,q被用户输入并且循环没有中断。 If there is also a better way to do this that would be great. 如果还有更好的方法可以做到这一点,那就太好了。

#include <stdio.h>
#include "CashRegister.h"
#include <stdlib.h>
#include <iostream>
#include <string>
using namespace std;

CashRegister::CashRegister(void)
{
}

CashRegister::~CashRegister(void)
{
}

void CashRegister::addItem(void)
{
string temp;
int k = 0;
int exit = 0;
CashRegister item[10];

for(int i = 0; i < 10; ++ i)
{
    item[i].price = 0.00;
}

cout << "Enter price of items. Up to 10 maximum\n" << endl;

while(item[9].price != 0.00 || temp != "q")
{
    cout << "Enter price of item number " << k + 1 << "\n" << endl;
    cin >> temp;
    cout << temp << endl;
    double tempPrice = (double)atof(temp.c_str());
    item[k].price = tempPrice;
    cout << "Price of item number " << k + 1 << " is $" << item[k].price << endl;
    ++k;
}

} }

Your while loop needs to read: 您的while循环需要阅读:

while(item[9].price != 0.00 && temp != "q")

The loop needs to continue while both conditions are true, so you need to say && not || 当两个条件都成立时,循环需要继续,因此您需要说&&而不是|| .

while(item[9].price != 0.00 || temp != "q")

Consider what this is saying. 考虑一下这是在说什么。 " Loop while price isn't 0 or temp isn't "q". " Now consider what has to occur for this to stop looping. 价格不为0 温度不为“ q”时循环。”现在,考虑要使循环停止发生什么。

You should use this to break loop : 您应该使用它来中断循环:

while(item[9].price != 0.00 && temp != "q")
{
  // ur stuff
}

Loop will iterate because item[9].price will contain some value other then 0.00 循环将迭代,因为item [9] .price将包含除0.00以外的一些值

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM