Welcome to the exciting world of C++ String Streams! In this comprehensive lesson, we'll dive deep into understanding and mastering this powerful tool. We'll start from the basics and gradually build up to advanced examples, making it suitable for both beginners and intermediates.
String streams are a part of the C++ Standard Template Library (STL). They provide a way to manipulate strings as if they were input/output streams. This makes it easier to read and write strings, especially in complex situations.
The std::stringstream class is the foundation of C++ string streams. It can be used to convert between a string and other data types.
Stream manipulators are functions that can be used with the std::stringstream to manipulate the output format. Some common stream manipulators are std::setw, std::setprecision, and std::fixed.
To create a string stream, we use the std::stringstream constructor. Here are two ways to do it:
std::stringstream myStream;std::stringstream myStream(std::ios::out);To write to a string stream, we use the << operator, just like we do with regular output streams.
std::stringstream myStream;
myStream << "Hello, World!";To read from a string stream, we use the >> operator, just like we do with regular input streams.
std::string myString;
std::stringstream myStream("Hello, World!");
myStream >> myString;Let's create a simple program that reads numbers from a string and calculates their sum.
#include <iostream>
#include <sstream>
#include <vector>
int main() {
std::string input = "1 2 3 4 5";
std::stringstream ss(input);
std::vector<int> numbers;
int num;
while (ss >> num) {
numbers.push_back(num);
}
int sum = 0;
for (const auto &number : numbers) {
sum += number;
}
std::cout << "The sum of numbers is: " << sum << std::endl;
return 0;
}What is the purpose of the `std::stringstream` class in C++?