码迷,mamicode.com
首页 > 编程语言 > 详细

C++ | from_string函数的写法

时间:2020-06-05 22:54:43      阅读:114      评论:0      收藏:0      [点我收藏+]

标签:amp   lca   return   class   code   out   const   typename   double   

C++标准库提供了to_string, 却没有from_string, 如何自己实现一个?

/**
 * @author hellcat
 * @time 2020.06.05
 * @file a.cpp
 * @hedername std
 * @return
 */
#include <iostream>
#include <string>
#include <sstream>

using namespace std;

struct bad_from_string : bad_cast {
    const char* what() const noexcept override { // 这里的函数签名视编译器而定
        return "bad cast from string";
    }
};

template<typename T>
T from_string(const string& s) {
    istringstream is(s);
    T t;
    if (!(is >> t)) throw bad_from_string();
    return t;
}

int main() {
    string s = "12414.322";
    string ss = to_string(11231);
    try {
        auto a = from_string<double>(s);
        cout << a << endl;
    } catch (exception& e) {
        cout << e.what() << endl;
    }
}

这里应用了异常处理机制, 避免auto a = from_string("CPP"); 这样代码的影响.

C++ | from_string函数的写法

标签:amp   lca   return   class   code   out   const   typename   double   

原文地址:https://www.cnblogs.com/tedukuri/p/13052414.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!