c++stringwhile-loop

How do I only accept specific string input


I want to write a code that finds the derivative to any function and want to take a user input on what type of function they're inputting is. Essentially I tried to write a while loop that only accept valid answers but the while loop isn't behaving as intended. Here is my code:

int main()
{
    std::cout << "Welcome to the differentiation calculator: "; 
    std::cout << std::endl; 
    std::cout << "Please input what type of function you have: Algebraic,Trigonometric,Exponential, Hyperbolic : " << std::endl;
    std::string UsersTypeOfFunction; 
    std::cin >> UsersTypeOfFunction; 

    while (UsersTypeOfFunction != "Hyperbolic" || UsersTypeOfFunction != "hyperbolic" || UsersTypeOfFunction != "Exponential" || UsersTypeOfFunction != "exponential" || UsersTypeOfFunction != "Trigonometric" || UsersTypeOfFunction != "trigonometric" || UsersTypeOfFunction != "Algebraic " || UsersTypeOfFunction != "algebraic")
    {
        std::cout << "Please input a Valid function type. "; 
        std::cin >> UsersTypeOfFunction; 
    }

    return 0; 
}

if my code is the issue please let me know


Solution

  • Although you got the correct explanation in the comment, you might go a step further and try to avoid redundant code.

    First, you could define a std::vector holding the allowed values:

    std::vector<std::string> functions = {
        "Hyperbolic",    "hyperbolic",
        "Exponential",   "exponential",
        "Trigonometric", "trigonometric"
    };
    

    then you can take advantage of the algorithm available in the C++ standard library. In this specific case, you could use std::find that can tell whether a given value can be found for instance in a vector.

    Since you have to enter at least once the value, you should use a do/while loop instead of a while loop. Putting all together, you could have e.g.

    #include <vector>
    #include <string>
    #include <algorithm>
    #include <iostream>
    
    int main()
    {
        std::cout << "Welcome to the differentiation calculator: ";
        std::cout << std::endl;
    
        std::vector<std::string> functions = {
            "Hyperbolic",    "hyperbolic",
            "Exponential",   "exponential",
            "Trigonometric", "trigonometric"
        };
    
        std::string UsersTypeOfFunction;
    
        do {
            std::cout << "Please input a Valid function type: ";
            std::cin >> UsersTypeOfFunction;
        } while (std::find(functions.begin(), functions.end(), UsersTypeOfFunction) == functions.end());
    }