且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

在C ++中将字符串转换为int,使用bool / fail

更新时间:2023-02-03 08:29:25

boost :: lexical_cast 。如果无法完成转换,则会抛出异常

Use boost::lexical_cast. If the cast cannot be done, it will throw an exception.

#include <boost/lexical_cast.hpp>
#include <iostream>
#include <string>

int main(void)
{
    std::string s;
    std::cin >> s;

    try
    {
        int i = boost::lexical_cast<int>(s);

        /* ... */
    }
    catch(...)
    {
        /* ... */
    }
}


没有提升:

#include <iostream>
#include <sstream>
#include <string>

int main(void)
{
    std::string s;
    std::cin >> s;

    try
    {
        std::stringstream ss(s);

        int i;
        if ((ss >> i).fail() || !(ss >> std::ws).eof())
        {
            throw std::bad_cast();
        }

        /* ... */
    }
    catch(...)
    {
        /* ... */
    }
}


伪造提升:

#include <iostream>
#include <sstream>
#include <string>

template <typename T>
T lexical_cast(const std::string& s)
{
    std::stringstream ss(s);

    T result;
    if ((ss >> result).fail() || !(ss >> std::ws).eof())
    {
        throw std::bad_cast();
    }

    return result;
}

int main(void)
{
    std::string s;
    std::cin >> s;

    try
    {
        int i = lexical_cast<int>(s);

        /* ... */
    }
    catch(...)
    {
        /* ... */
    }
}


如果你想要这些函数的no-throw版本,你必须捕获适当的异常(我不认为 boost :: lexical_cast -throw version),类似这样的:

If you want no-throw versions of these functions, you'll have to catch the appropriate exceptions (I don't think boost::lexical_cast provides a no-throw version), something like this:

#include <iostream>
#include <sstream>
#include <string>

template <typename T>
T lexical_cast(const std::string& s)
{
    std::stringstream ss(s);

    T result;
    if ((ss >> result).fail() || !(ss >> std::ws).eof())
    {
    	throw std::bad_cast();
    }

    return result;
}

template <typename T>
bool lexical_cast(const std::string& s, T& t)
{
    try
    {
    	// code-reuse! you could wrap
    	// boost::lexical_cast up like
    	// this as well
    	t = lexical_cast<T>(s);

    	return true;
    }
    catch (const std::bad_cast& e)
    {
    	return false;
    }
}

int main(void)
{
    std::string s;
    std::cin >> s;

    int i;
    if (!lexical_cast(s, i))
    {
    	std::cout << "Bad cast." << std::endl;
    }	
}