2012-03-21 82 views

回答

2
在C++ 98

你可以做

std::string str("1234"); 
int i; 
std::stringstream ss(str); 
ss >> i; 
在C++

11,你应该做的:

std::string str("1234"); 
int i=std::stoi(str); 
-1

更C++ - 的方式这样做的:

#include <sstream> 
#include <string> 

// Converts a string to anything. 
template<typename T> 
T to(const std::string& s) 
{ 
    std::stringstream ss(s); 
    T ret; 
    ss >> ret; 
    return ret; 
} 

// And with a default value for not-convertible strings: 
template<typename T> 
T to(const std::string& s, T default_) 
{ 
    std::stringstream ss(s); 
    ss >> default_; 
    return default_; 
} 

使用方法如下:

int i = to<int>("123"); 
assert(i == 123); 
int j = to<int>("Not an integer", 123); 
assert(j == 123); 

并且将其扩展到支持任意类型你们的:

struct Vec3 {float x, y, z;}; 

template<class T> 
T& operator>>(T& f, Vec3& v) { 
    f >> v.x >> v.y >> v.z; 
    return f; 
} 

// Somewhere else: 
Vec3 v = to<Vec3>("1.0 2.0 3.0"); 
相关问题