Output error when input isn't a number. C++

前端 未结 5 1872
野性不改
野性不改 2021-01-28 07:47

I am making a function that takes a number from the user\'s input and finds the absolute value of it. I want to make it return an error if the user inputs anything other than j

5条回答
  •  臣服心动
    2021-01-28 08:24

    If you are actually trying to program in idiomatic C++, ignore the (intentionally?) bad advice you are being given. Especially the answers pointing you toward C functions. C++ may be largely backwards-compatible with C, but its soul is a totally different language.

    Your question is so foundational as to make for a terrible homework assignment. Especially if you're so adrift that you don't know to avoid conio.h and other tragedies. So I'm just going to write out a solution here:

    #include 
    #include 
    
    // Your function is presumably something like this
    // although maybe you are just using integers instead of floats
    float myAbs(const float x) {
        if (x >= 0) {
            return x;
        } else {
            return -x;
        }
    }
    
    int main(int argc, char* argv[]) {
        // give a greeting message followed by a newline
        std::cout << "Enter values to get |value|, or type 'quit'" << std::endl;
    
        // loop forever until the code hits a BREAK
        while (true) {
            // attempt to get the float value from the standard input
            float value;
            std::cin >> value;
    
            // check to see if the input stream read the input as a number
            if (std::cin.good()) {
    
                // All is well, output it
                std::cout << "Absolute value is " << myAbs(value) << std::endl;
    
            } else {
    
                // the input couldn't successfully be turned into a number, so the
                // characters that were in the buffer that couldn't convert are
                // still sitting there unprocessed.  We can read them as a string
                // and look for the "quit"
    
                // clear the error status of the standard input so we can read
                std::cin.clear();
    
                std::string str;
                std::cin >> str;
    
                // Break out of the loop if we see the string 'quit'
                if (str == "quit") {
                    break;
                }
    
                // some other non-number string.  give error followed by newline
                std::cout << "Invalid input (type 'quit' to exit)" << std::endl;
            }
        }
    
        return 0;
    }
    

    This lets you use the natural abilities of the iostream classes. They can notice when they couldn't automatically convert what a user entered into the format you wanted, and give you a chance to just throw up your hands with an error -or- try interpreting the unprocessed input a different way.

提交回复
热议问题