如何将char数组转换为整数/双/长类型?

时间:2011-12-04 15:40:29

标签: c++

  

可能重复:
  How to convert a number to string and vice versa in C++

如何将char数组转换为整数/双/长类型-atol()函数?

5 个答案:

答案 0 :(得分:10)

Boost.LexicalCast

boost::lexical_cast<int>("42");

(C++11)

std::stoi("42");

另外,除非是互操作,否则不要使用char数组。请改用std::string。也不要使用ato*函数,即使在C语言中,它们也会按设计破坏,因为它们无法正确发出错误信号。

答案 1 :(得分:5)

自己编写这样一个函数是一个很好的练习:

unsigned parse_int(const char * p)
{
    unsigned result = 0;
    unsigned digit;
    while ((digit = *p++ - '0') < 10)
    {
        result = result * 10 + digit;
    }    
    return result;
}

当然,您应该更喜欢现实代码中现有的库设施。

答案 2 :(得分:2)

使用C++ Streams

std::string hello("123"); 
std::stringstream str(hello); 
int x;  
str >> x;  
if (!str) 
{      
   // The conversion failed.      
} 

答案 3 :(得分:1)

template<class In, class Out>
static Out lexical_cast(const In& inputValue)
        {
    Out result;

    std::stringstream stream(std::stringstream::in | std::stringstream::out);
    stream << inputValue;
    stream >> result;
    if (stream.fail() || !stream.eof()) {
        throw bad_cast("Cast failed");
    }

    return result;
}

使用它:

int val = lexical_cast< std::string, int >( "123" );

答案 4 :(得分:0)

你的意思是如何将它们转换为整数?您无法将字符数组转换为语言级别的函数 - 也许您可以使用某些编译器特定的内联汇编语法。要转换为整数,您可以使用atoi

int i = atoi("123");`

strtol

long l = strtol("123", NULL, 10);