Converting Between std::stringstream, std::string, and char*
In C++ programming, it is often necessary to convert between different string representations, primarily involving three types: std::stringstream, std::string, and char*. I will explain the conversion methods and application scenarios between them in detail.
1. Conversion between std::string and std::stringstream
From std::string to std::stringstream:
cpp#include <sstream> #include <string> std::string str = "Hello World"; std::stringstream ss; ss << str; // Insert the std::string object str into the stringstream
From std::stringstream to std::string:
cppstd::stringstream ss; ss << "Hello World"; std::string str = ss.str(); // Use the str() method of stringstream to obtain a std::string
2. Conversion between std::string and char*
From std::string to char:*
cpp#include <string> std::string str = "Hello World"; const char* cstr = str.c_str(); // Use the c_str() method to obtain the corresponding const char* pointer
From char to std::string:*
cppconst char* cstr = "Hello World"; std::string str(cstr); // Initialize a std::string object directly with char*
3. Conversion between std::stringstream and char*
From char to std::stringstream:*
cppconst char* cstr = "Hello World"; std::stringstream ss; ss << cstr; // Insert the content of const char* into the stringstream
From std::stringstream to char:*
This conversion is not directly supported because std::stringstream is typically converted to std::string first, and then to char*. The process is as follows:
cppstd::stringstream ss; ss << "Hello World"; std::string str = ss.str(); const char* cstr = str.c_str();
Application Scenario Example:
Suppose we are developing a feature that reads lines from a text file, processes them, and writes them to another file. Here, we might use std::stringstream for string concatenation, std::string for intermediate storage, and interact with C-style I/O functions via char*.
cpp#include <fstream> #include <sstream> #include <iostream> #include <string> int main() { std::ifstream infile("input.txt"); std::ofstream outfile("output.txt"); std::string line; while (std::getline(infile, line)) { std::stringstream ss; ss << "Processed: " << line; std::string processedLine = ss.str(); outfile << processedLine << std::endl; } infile.close(); outfile.close(); return 0; }
In this example, we utilize std::stringstream to construct new strings, std::string to store these strings, and output them to files. Although char* is not directly used here, we can employ .c_str() when compatibility with C-style string APIs is required.