且构网

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

如何在C ++中将字符串向量转换为整数向量?

更新时间:2023-02-03 10:13:34

有多种将字符串转换为int的方法.

There are mulitple ways of converting a string to an int.

解决方案1:使用旧版C功能

Solution 1: Using Legacy C functionality

int main()
{
    //char hello[5];     
    //hello = "12345";   --->This wont compile

    char hello[] = "12345";

    Printf("My number is: %d", atoi(hello)); 

    return 0;
}

解决方案2:使用 lexical_cast (最合适和最简单)

Solution 2: Using lexical_cast(Most Appropriate & simplest)

int x = boost::lexical_cast<int>("12345"); 

try-catch 包围以捕获异常.

解决方案3:使用 C ++流

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