You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在C++中实现类似Python的格式化字符串插值功能

C++实现类似Python f-string的字符串插值方案

你代码中已经引入了C++20的<format>标准库,这是最接近Python f-string使用体验的实现,直接修改代码如下即可:

#include <iostream>
#include <Windows.h>
#include <TlHelp32.h>
#include <string>
#include <format>

using namespace std;

#pragma warning(disable:4996)

int main() {
    char* p = getenv("USERPROFILE");
    // 先校验环境变量是否读取成功,避免空指针引发程序崩溃
    if (p == nullptr) {
        cout << "读取USERPROFILE环境变量失败" << endl;
        system("pause");
        return 1;
    }
    // std::format用法和f-string几乎一致,{}做占位符,后续按顺序传入变量即可
    string dllpath = format("C:\\Users\\{}\\Desktop\\ExterTi\\req\\sk.dll", p);
    cout << dllpath << endl;
    system("pause");
    return 0;
}

如果你的编译器暂不支持C++20标准,可以用以下两种替代方案:

方案1:std::string直接拼接(兼容性最好,无额外依赖)

string dllpath = string("C:\\Users\\") + p + "\\Desktop\\ExterTi\\req\\sk.dll";

如果是支持C++14的编译器也可以用字符串字面量后缀简化写法:

string dllpath = "C:\\Users\\"s + p + "\\Desktop\\ExterTi\\req\\sk.dll";

方案2:使用sprintf格式化(适合习惯C风格写法的场景)

char dllpath_buf[1024] = {0};
sprintf(dllpath_buf, "C:\\Users\\%s\\Desktop\\ExterTi\\req\\sk.dll", p);
const char* dllpath = dllpath_buf;

内容的提问来源于stack exchange,提问作者Kanot

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 23:39:03