Why doesn't C++ reimplement C standard functions with C++ elements/style?

后端 未结 10 2583
花落未央
花落未央 2020-12-10 05:46

For a specific example, consider atoi(const std::string &). This is very frustrating, since we as programmers would need to use it so much.

10条回答
  •  一整个雨季
    2020-12-10 06:15

    There's no good way to know if atoi fails. It always returns an integer. Is that integer a valid conversion? Or is the 0 or -1 or whatever indicating an error? Yes it could throw an exception, but that would change the original contract, and you'd have to update all your code to catch the exception (which is what the OP is complaining about).

    If translation is too time consuming, write your own atoi:

    int atoi(const std::string& str)
    {
        std::istringstream stream(str);
        int ret = 0;
        stream >> ret;
        return ret;
    }
    

提交回复
热议问题