How is the string format used in C++?
In C++, there are no built-in string formatting functions, but you can use other methods to format strings. One common method is to use the std::stringstream class to create a string stream, then write the data that needs to be formatted into the stream. For example:
#include <iostream>
#include <string>
#include <sstream>
int main() {
int num = 42;
double pi = 3.14159;
std::string name = "Alice";
std::stringstream ss;
ss << "Number: " << num << ", Pi: " << pi << ", Name: " << name;
std::string formattedString = ss.str();
std::cout << formattedString << std::endl;
return 0;
}
In this example, we use the std::stringstream class to format an integer, a double precision floating point number, and a string into one string. Finally, we obtain the formatted string by calling ss.str() method.
In addition, C++11 introduces the std::to_string function, which makes it easy to convert basic data types to strings. For example:
int num = 42;
std::string numStr = std::to_string(num);
This method is suitable for converting basic data types such as integers and floating point numbers into strings.
More tutorials
Converting a C++ string to uppercase and lowercase.(Opens in a new browser tab)
2D array for C++ implementation(Opens in a new browser tab)
How to initialize a C language second-level pointer?(Opens in a new browser tab)
Converting a Python string to an integer and vice versa.(Opens in a new browser tab)
Convert time to hours, minutes, and seconds in python(Opens in a new browser tab)