一、format庫的簡介
1、format庫是C++11格式化字符串的一種解決方案,它的設計目標是提供簡單、便捷的格式化語法,並且不需要調用大量的函數來實現字符串的格式化。
2、format庫可以被看作是一個功能強大的printf的替代品。在使用上它更加靈活,更加安全,而且能夠提供更加友好的錯誤提示。
3、format庫的使用方式和Python的字符串格式化方式非常相似,適合需要頻繁使用字符串格式化的場景。
二、格式化字符串的基本語法
1、格式化字符串的基本語法為「{index:format}」,其中index表示格式化參數的下標,format表示格式化參數的格式化方式。
2、在format中,輸入參數的下標是從0開始的。
3、format參數中如果出現「{{」或「}}」表示轉義字符「{」或「}」。
#include <fmt/format.h> #include <iostream> int main(){ std::cout << fmt::format("{} {} {}!\n", "Hello", "World", 123); std::cout << fmt::format("{2} {1} {0}!\n", "Hello", "World", 123); std::cout << fmt::format("{0:+} {0:-} {0:#}\n", 123); std::cout << fmt::format("{0:.3f} {0:7.3f}\n", 3.1415926535); std::cout << fmt::format("{{ }}\n"); return 0; }
三、format的錯誤提示
1、在使用format格式化字符串時,如果有參數過多或過少,format庫將會拋出一個異常。
2、同時,format庫還會在輸出字符串中顯示「(error)」提示,同時提供友好的錯誤提示信息。
#include <fmt/format.h> #include <iostream> int main(){ try{ std::cout << fmt::format("{} {} {} {}!\n", "Hello", "World", 123); }catch(fmt::format_error& e){ std::cout << "Format error: " << e.what() << std::endl; } return 0; }
四、format的類型支持
1、format支持的格式化類型包括整數、浮點數、字符串和自定義類型等。
2、在format中可以通過添加「:」後的字符來定義格式化類型。
3、format還支持用戶自定義類型的格式化方法,可以通過重載「format」方法來實現。
#include <fmt/format.h> #include <iostream> #include <complex> template <typename T> struct fmt::formatter<std::complex<T>>{ char presentation = 'g'; auto parse(fmt::format_parse_context& ctx){ auto it = ctx.begin(), end = ctx.end(); if(it != end && (*it == 'e' || *it == 'f' || *it == 'g')) presentation = *it++; if(it != end && *it != '}') throw fmt::format_error("invalid format"); return it; } auto format(std::complex<T> c, fmt::format_context& ctx){ if(presentation == 'e'){ return fmt::format_to(ctx.out(), "({}e{:+.3g}, {}e{:+.3g})", c.real(), c.imag(), std::abs(c), std::arg(c)); }else if(presentation == 'f'){ return fmt::format_to(ctx.out(), "({:.3f}, {:.3f})", c.real(), c.imag()); }else{ return fmt::format_to(ctx.out(), "({:.3g}, {:.3g})", c.real(), c.imag()); } } }; int main(){ std::cout << fmt::format("{}", std::complex<float>(1,2)) << std::endl; std::cout << fmt::format("{:f}", std::complex<float>(1,2)) << std::endl; std::cout << fmt::format("{:e}", std::complex<float>(1,2)) << std::endl; return 0; }
五、format的輸出方式
1、format支持多種輸出方式,包括輸出到字符串、文件、網絡等。
2、在輸出到文件時,可以使用fmt::print函數來重定向輸出流。
3、在輸出到網絡時,可以使用fmt::format_to函數來自動擴展內存空間以適應數據量。
#include <fmt/format.h> #include <iostream> #include <fstream> int main(){ std::string str = fmt::format("{} {} {}!\n", "Hello", "World", 123); fmt::print(str); std::ofstream fout("output.txt"); fmt::print(fout, "Hello, World!\n"); fmt::print("Hello, Network!\n"); return 0; }
原創文章,作者:FUHHN,如若轉載,請註明出處:https://www.506064.com/zh-hk/n/370920.html