首页 > 解决方案 > std::string == operator not working in code

问题描述

So I am making a simple calculator using c++ which inputs a string from the user and takes that input as the operation.

std::cout<<"Enter your operation: ";
std::string operation;
std::cin>>operation;
while(operation != string("+")|| operation != string("-") || operation != string("*"))
{
    std::cout<<"Invalid operation! Please enter a valid one: ";
    std::cin>>operation;
}

However no matter what I input, I get the error message "Invalid operation! Please enter a valid one: ". Please help me out here, thanks!

标签: c++stringloops

解决方案


你几乎拥有它。您只需要在循环条件中使用布尔运算符 &&不是或: ||

std::cout<<"Enter your operation: ";
std::string operation;
std::cin>>operation;
while(operation != string("+") && operation != string("-") && operation != string("*"))
{
    std::cout<<"Invalid operation! Please enter a valid one: ";
    std::cin>>operation;
}

只要operationis not a+并且 is not a-并且 is not a ,您就想继续循环*。因此,如果它是其中之一,则条件将是false并且您的循环将结束。


推荐阅读