C++ | from_string函数的写法

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"); 这样代码的影响.

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

欢迎关注

微信关注下方公众号,第一时间获取干货硬货;公众号内回复【pdf】免费获取数百本计算机经典书籍;

也有高质量的技术群,里面有嵌入式、搜广推等BAT大佬

    C++ | from_string函数的写法

原创文章受到原创版权保护。转载请注明出处:https://www.ccppcoding.com/archives/353019

非原创文章文中已经注明原地址,如有侵权,联系删除

关注公众号【高性能架构探索】,第一时间获取最新文章

转载文章受原作者版权保护。转载请注明原作者出处!

(0)
上一篇 2023年3月2日 上午7:50
下一篇 2023年3月2日 上午7:50

相关推荐