输入不是数字时输出错误。 C++

2024-04-17

我正在创建一个函数,它从用户的输入中获取一个数字并找到它的绝对值。如果用户输入数字以外的任何内容,我想让它返回错误。我该怎么做呢?

(我知道这对很多人来说可能是一个简单的问题,但我正在上第一堂 C++ 编程课,所以我知之甚少。任何帮助将不胜感激。)


如果您实际上正在尝试使用惯用的 C++ 进行编程,请忽略(故意的?)向您提供的糟糕建议。尤其是那些将您引向 C 函数的答案。 C++ 可能在很大程度上与 C 向后兼容,但它的灵魂是一种完全不同的语言。

你的问题太基础了,以至于构成了一项糟糕的家庭作业。尤其是当你如此漂泊以至于你不知道要避开时conio.h http://en.wikipedia.org/wiki/Conio.h以及其他悲剧。所以我就在这里写一个解决方案:

#include <iostream>
#include <string>

// 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;
}

这使您可以使用 iostream 类的天然功能。他们可以注意到何时无法自动将用户输入的内容转换为您想要的格式,并让您有机会因错误而举手 - 或者尝试以不同的方式解释未处理的输入。

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

输入不是数字时输出错误。 C++ 的相关文章

随机推荐