C++中的字符串插值可以通过使用格式化字符串来实现。格式化字符串使用特殊的占位符来表示要插入的值。

例如,可以使用%d来表示一个整数值,%f来表示一个浮点数值,%s来表示一个字符串值等等。

下面是一个使用格式化字符串进行字符串插值的例子:

#include <iostream>
#include <string>

int main() {
    std::string name = "Alice";
    int age = 30;
    float height = 1.65f;
    
    std::string message = "My name is %s, I am %d years old and %.2f meters tall.";
    printf(message.c_str(), name.c_str(), age, height);
    
    return 0;
}

在上面的例子中,我们使用了三个占位符来表示要插入的值。%s表示字符串值,所以我们需要使用c_str()方法将std::string类型转换为C风格字符串。%d%.2f分别表示整数值和带有两位小数的浮点数值。

输出结果为:

My name is Alice, I am 30 years old and 1.65 meters tall.

除了使用printf()函数外,我们还可以使用std::cout对象和<<运算符进行字符串插值。下面是一个使用std::cout对象进行字符串插值的例子:

#include <iostream>
#include <string>

int main() {
    std::string name = "Alice";
    int age = 30;
    float height = 1.65f;
    
    std::cout << "My name is " << name << ", I am " << age << " years old and " << height << " meters tall." << std::endl;
    
    return 0;
}

输出结果与之前的例子相同。

C++的字符串插值

原文地址: http://www.cveoy.top/t/topic/bykh 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录