C++ 文字列フォーマットの基本と実践テクニック

C++では、std::stringstreamまたはprintf関数を使用して文字列をフォーマットすることができます。

std::stringstreamの使用:

#include <iostream>
#include <sstream>

int main() {
    std::stringstream ss;
    int num = 10;
    float f = 3.14;
    std::string str = "Hello";

    ss << "Number: " << num << ", Float: " << f << ", String: " << str;

    std::string formatted_str = ss.str();
    std::cout << formatted_str << std::endl;

    return 0;
}

printf関数を使用する:

#include <iostream>
#include <cstdio>

int main() {
    int num = 10;
    float f = 3.14;
    std::string str = "Hello";

    char buffer[100];
    std::sprintf(buffer, "Number: %d, Float: %.2f, String: %s", num, f, str.c_str());

    std::string formatted_str = buffer;
    std::cout << formatted_str << std::endl;

    return 0;
}

std::stringstreamやprintf関数を使用して、文字列をフォーマットすることができます。

bannerAds