zoukankan      html  css  js  c++  java
  • C++字符串、浮点数转换小demo

    #include <iostream>
    #include <iomanip>
    #include <string>
    
    template<typename T>
    T string_to_number(const std::string &numberAsString) {
        using namespace std;
        T valor;
    
        stringstream stream(numberAsString);
        stream >> valor;
        if (stream.fail()) {
            throw runtime_error("string_to_number(): " + numberAsString);
        }
        return valor;
    }
    
    template<typename T>
    std::string num_to_string_with_precision(const T a_value, const int n = 6) {
        using namespace std;
        std::ostringstream out;
        std::fixed(out);
        out << std::setprecision(n) << a_value;
        return out.str();
    }
    
    int main() {
        using namespace std;
    
        try {
            std::string str_num = "1997.1009f";
            double d = string_to_number<double>(str_num);
            cout << std::fixed << std::setprecision(4);
            cout << d << endl;
    
    //        double d2 = stod(str_num);
    //        cout.width(3);
    //        cout.setf(ios::fixed);
    //        cout.precision(4);
    //        cout << d2 << endl;
    
            string s = num_to_string_with_precision(d, 4);
            cout << s << endl;
        } catch (exception &e) {
            std::cerr << "Error occurred, " << e.what() << std::endl;
        }
    
        return 0;
    }
    

      运行结果:

  • 相关阅读:
    python3-while与if
    python3-while与continue
    python3-password在输入密码时隐藏密码
    input与字符串格式化
    for与break的用法
    bochs 2.6.8 常用命令集合
    关于8086中的jmp near ptr原理
    如何学习Python课程
    微信公众号去除密码安全提示
    模块的使用
  • 原文地址:https://www.cnblogs.com/areful/p/11583777.html
Copyright © 2011-2022 走看看