首页 > 编程语言 > 详细

C++ | from_string函数的写法

时间:2020-06-05 22:23:45      阅读:103      评论:0      收藏:0      [点我收藏+]

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函数的写法

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

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!