我正在锻炼:
为myPrintf模板函数添加代码,该代码检查格式字符串中参数类型和类型规范的匹配情况。仅将%d限制为int的转换,然后将%f限制为float的转换,将%s限制为const char *的转换。
这是我的代码:
#include <iostream>
#include <string>
#include <type_traits>
#include <cstring>
#include <algorithm>
#include <regex>
using namespace std;
最后,我将只打印该字符串,并将所有%d%f%s更改为变量的值
auto myPrintf(const char* x){
cout<< x;
}
这是我的模板:
template<typename T ,typename... Args>
auto myPrintf(const char* x, T t, Args... args){
std::regex e("[%].");
std::cmatch cm;
if (std::regex_search (x,cm,e))
{
if (std::is_integral_v<T> ){
const char* d="%d";
if (strcmp(cm,d)==0){
std::regex_replace (x,e,t,std::regex_constants::format_first_only);
}
if(std::is_floating_point_v<T> ){
const char* f="%f";
if (strcmp(cm,f)==0){
std::regex_replace (x,e,t,std::regex_constants::format_first_only);
}
}
if constexpr (std::is_same_v<const char*, T>) {
const char* s="%s";
if (strcmp(cm,s)==0){
std::regex_replace (x,e,t,std::regex_constants::format_first_only);
}
}
}
return myPrintf(x,args...);
}
int main () {
int i1 = 5, i2 = 7;
float f1 = 5.4, f2 = 7.3;
const char* s1 = "ABC";
const char* s2 = "PQR";
myPrintf("Print with no args");
myPrintf("Print mix with err -> str = %s, int = %d, flo = %f, str = %s, int = %d",
s1, i1, f1, i1, i2);
return 0;
}
请给我我用来替换const char * string中的值的函数。
编辑:
我现在遇到此错误:无法将参数'1'的'const value_type {aka const std :: sub_match}'转换为'const char *'到'int strcmp(const char *,const char *)'>
谢谢
答案 0 :(得分:1)
代码的固定版本:
auto myPrintf(const std::string& x){
std::cout<< x;
}
template<typename T ,typename... Args>
auto myPrintf(std::string x, T t, Args... args){
std::regex e("[%].");
std::smatch cm;
if (std::regex_search (x,cm,e))
{
if constexpr (std::is_integral_v<T> ){
const char* d="%d";
if (strcmp(cm[0].str().c_str(),d)==0){
x = std::regex_replace (x,e, std::to_string(t),std::regex_constants::format_first_only);
}
}
if constexpr (std::is_floating_point_v<T> ){
const char* f="%f";
if (strcmp(cm[0].str().c_str(),f)==0){
x = std::regex_replace (x,e,std::to_string(t),std::regex_constants::format_first_only);
}
}
if constexpr (std::is_same_v<const char*, T>) {
const char* s="%s";
if (strcmp(cm[0].str().c_str(),s)==0){
x = std::regex_replace (x,e,t,std::regex_constants::format_first_only);
}
}
}
return myPrintf(x,args...);
}