注册 登录
编程论坛 C++教室

关于类型转换问题。

ytiantian 发布于 2013-05-08 10:18, 367 次点击
请问怎么将string类型转换成int、char、long int 等任意类型。parse函数怎么用?atoi怎么用,还有怎么当键入一个数值的时候、不确定什么类型应该定义成什么样的
1 回复
#2
rjsp2013-05-08 10:51
parse函数怎么用? --- 没听说过parse函数
怎么当键入一个数值的时候、不确定什么类型应该定义成什么样的 --- 逻辑不通。但你既然可以键入,那就可以当成字符串

程序代码:
#include <sstream>
#include <exception>

struct bad_lexical_cast : public std::exception {
};

template<typename Target, typename Source>
Target lexical_cast(Source arg) {
    std::stringstream interpreter;
    Target result;
    if( !(interpreter<<arg) || !(interpreter>>result) || !(interpreter>>std::ws).eof() )
        throw bad_lexical_cast();
    return result;
}

#include <iostream>
#include <cstdlib>

using namespace std;

int main()
{
    int a = lexical_cast<int,const char*>("123");
    double b = lexical_cast<double,const char*>("123.456");
    int c = atoi( "456" );
    cout << a << '\n'
         << b << '\n'
         << c << endl;

    return 0;
}

1