Yes, you can use string streams with custom data types in C++. To do this, you need to overload the insertion (<<
) and extraction (>>
) operators for your custom types.
This allows your data types to be inserted into and extracted from string streams just like built-in types.
To insert a custom data type into a string stream, overload the <<
operator. Here’s an example with a custom Person
 class:
#include <iostream>
#include <sstream>
class Person {
public:
Person(const std::string& name, int age)
: Name{name}, Age{age} {}
friend std::ostream& operator<<(
std::ostream& os, const Person& person);
private:
std::string Name;
int Age;
};
std::ostream& operator<<(
std::ostream& os, const Person& person
) {
os << "Name: " << person.Name
<< ", Age: " << person.Age;
return os;
}
int main() {
Person p{"Alice", 30};
std::ostringstream Stream;
Stream << p;
std::cout << Stream.str();
}
Name: Alice, Age: 30
To extract a custom data type from a string stream, overload the >>
operator. Here’s an example:
#include <iostream>
#include <sstream>
class Person {
public:
Person() : Name{""}, Age{0} {}
friend std::istream& operator>>(
std::istream& is, Person& person);
std::string Name;
int Age;
};
std::istream& operator>>(
std::istream& is, Person& person
) {
is >> person.Name >> person.Age;
return is;
}
int main() {
std::istringstream Stream{"Bob 25"};
Person p;
Stream >> p;
std::cout << "Extracted Person - Name: "
<< p.Name << ", Age: " << p.Age;
}
Extracted Person - Name: Bob, Age: 25
Combining both insertion and extraction operators, you can serialize and deserialize your custom types easily:
#include <iostream>
#include <sstream>
class Person {
public:
Person() : Name{""}, Age{0} {}
Person(const std::string& name, int age)
: Name{name}, Age{age} {}
friend std::ostream& operator<<(
std::ostream& os, const Person& person
);
friend std::istream& operator>>(
std::istream& is, Person& person
);
std::string Name;
int Age;
};
std::ostream& operator<<(
std::ostream& os, const Person& person
) {
os << person.Name << " " << person.Age;
return os;
}
std::istream& operator>>(
std::istream& is, Person& person
) {
is >> person.Name >> person.Age;
return is;
}
int main() {
Person p1{"Charlie", 40};
std::ostringstream outStream;
outStream << p1;
std::istringstream inStream(outStream.str());
Person p2;
inStream >> p2;
std::cout << "Serialized: "
<< outStream.str() << "\n";
std::cout << "Deserialized - Name: "
<< p2.Name << ", Age: " << p2.Age;
}
Serialized: Charlie 40
Deserialized - Name: Charlie, Age: 40
<<
for insertion and >>
for extraction.By overloading the appropriate operators, you can integrate custom data types with string streams effectively, making your code more flexible and powerful.
Answers to questions are automatically generated and may not have been reviewed.
A detailed guide to C++ String Streams using std::stringstream
. Covers basic use cases, stream position seeking, and open modes.