# sstream

***

**1. Reading and Writing to a String Stream:**

```cpp
#include <sstream>
std::stringstream ss;
std::string str = "Hello World";

// Write to the stream
ss << str;

// Read from the stream
std::string read_str;
ss >> read_str;

// Check if the read string matches the original string
if (read_str == str)
  std::cout << "Strings match!\n";
```

**2. Formatting Output:**

```cpp
#include <sstream>
using namespace std;

ostringstream mystream;

// Format and write float with precision of 2 decimal places
mystream << std::fixed << std::setprecision(2) << 3.14159;

// Retrieve the formatted string
string formatted_str = mystream.str();
```

**3. Parsing Input:**

```cpp
#include <sstream>
using namespace std;

istringstream mystream("100 200 300");
int num1, num2, num3;

// Read and parse the numbers
mystream >> num1 >> num2 >> num3;

// Print the parsed numbers
cout << num1 << " " << num2 << " " << num3 << endl;
```

**4. Converting Numbers to Strings:**

```cpp
#include <sstream>
using namespace std;

ostringstream mystream;

// Convert an integer to a string
mystream << 12345;

// Retrieve the string representation
string num_str = mystream.str();
```

**5. Tokenizing a String:**

```cpp
#include <sstream>
using namespace std;

istringstream mystream("This is a test string");
vector<string> tokens;
string token;

while (mystream >> token)
{
  tokens.push_back(token);
}
```

**6. Converting String to Lowercase/Uppercase:**

```cpp
#include <sstream>
using namespace std;

ostringstream mystream;

// Convert a string to lowercase
mystream << "HELLO WORLD" << std::setfill('a');

// Retrieve the lowercase string
string lowercase_str = mystream.str();
```

**7. Splitting a String by Delimiter:**

```cpp
#include <sstream>
using namespace std;

istringstream mystream("a,b,c,d");
vector<string> tokens;
string token;

while (getline(mystream, token, ','))
{
  tokens.push_back(token);
}
```

**8. Reading from a File into a String Stream:**

```cpp
#include <sstream>
#include <fstream>
using namespace std;

ifstream infile("my_file.txt");
ostringstream mystream;

// Read the file into the stream
mystream << infile.rdbuf();

// Retrieve the string representation of the file contents
string file_contents = mystream.str();
```

**9. Writing to a File from a String Stream:**

```cpp
#include <sstream>
#include <fstream>
using namespace std;

ofstream outfile("my_file.txt");
ostringstream mystream;

// Write a string to the stream
mystream << "Hello World";

// Write the stream to the file
outfile << mystream.str();
```

**10. Using String Stream for Debugging:**

```cpp
#include <sstream>
using namespace std;

ostringstream mystream;

// Log a message to a string stream
mystream << "Error occurred: " << err_msg;

// Retrieve the logged message and print it to the console
string log_message = mystream.str();
cout << log_message << endl;
```

**11. Creating a CSV File:**

```cpp
#include <sstream>
#include <fstream>
using namespace std;

ofstream csv_file("output.csv");

// Create a string stream for each line
ostringstream line1, line2, line3;

// Add data to each line
line1 << "Name,Age" << endl;
line2 << "John,30" << endl;
line3 << "Jane,25" << endl;

// Write the lines to the CSV file
csv_file << line1.str() << line2.str() << line3.str();
```

**12. Parsing XML Using String Stream:**

```cpp
#include <sstream>
#include <pugixml.hpp>
using namespace std;

istringstream xml_stream;
pugi::xml_document doc;

// Load XML from string stream
xml_stream.str(xml_source);
doc.load(xml_stream);
```

**13. Converting a Map to a String:**

```cpp
#include <sstream>
#include <map>
using namespace std;

map<string, int> my_map = {{"a", 1}, {"b", 2}, {"c", 3}};
ostringstream mystream;

// Convert map to a string
for (const auto& item : my_map)
{
  mystream << item.first << ":" << item.second << endl;
}

// Retrieve the string representation of the map
string map_str = mystream.str();
```

**14. Converting a Vector to a String:**

```cpp
#include <sstream>
#include <vector>
using namespace std;

vector<int> my_vector = {1, 2, 3, 4, 5};
ostringstream mystream;

// Convert vector to a string
for (const auto& item : my_vector)
{
  mystream << item << " ";
}

// Retrieve the string representation of the vector
string vector_str = mystream.str();
```

**15. Creating a JSON String from an Object:**

```cpp
#include <sstream>
#include <nlohmann/json.hpp>
using namespace std;

struct Person
{
  string name;
  int age;
};

nlohmann::json to_json(Person person)
{
  return nlohmann::json{{"name", person.name}, {"age", person.age}};
}

int main()
{
  Person john = {"John", 30};
  ostringstream mystream;
  mystream << to_json(john);
  string json_str = mystream.str();
}
```

**16. Parsing JSON String into an Object:**

```cpp
#include <sstream>
#include <nlohmann/json.hpp>
using namespace std;

struct Person
{
  string name;
  int age;
};

Person from_json(const nlohmann::json& json)
{
  return Person{json["name"], json["age"]};
}

int main()
{
  string json_str = "{\"name\": \"John\", \"age\": 30}";
  istringstream mystream(json_str);
  nlohmann::json json;
  mystream >> json;
  Person john = from_json(json);
}
```

**17. Creating a Custom String Delimiter:**

```cpp
#include <sstream>
using namespace std;

ostringstream mystream;

// Create a custom string delimiter
mystream.imbue(locale("en_US.UTF-8"));
mystream.imbue(locale(mystream.getloc(), new delim('\t')));

// Write data to the stream using the custom delimiter
mystream << "John\t30\tMale";
```

**18. Parsing a Fixed-Width File:**

```cpp
#include <sstream>
#include <vector>
using namespace std;

istringstream mystream("1234567890John Doe");
vector<string> fields;
string field;

while (mystream.read(&field, 10))
{
  fields.push_back(field);
}
```

**19. Reading a Delimited File into a Vector of Vectors:**

```cpp
#include <sstream>
#include <vector>
using namespace std;

ifstream infile("data.csv");
vector<vector<string>> data;
string line;

while (getline(infile, line))
{
  istringstream mystream(line);
  vector<string> row;
  string field;

  while (getline(mystream, field, ','))
  {
    row.push_back(field);
  }

  data.push_back(row);
}
```

**20. Calculating Statistics from a Data File:**

```cpp
#include <sstream>
#include <vector>
#include <numeric>
using namespace std;

ifstream infile("numbers.txt");
vector<int> numbers;
int num;

while (infile >> num)
{
  numbers.push_back(num);
}

ostringstream mystream;
mystream << "Sum: " << accumulate(numbers.begin(), numbers.end(), 0) << endl;
mystream << "Average: " << accumulate(numbers.begin(), numbers.end(), 0.0) / numbers.size() << endl;
```

**21. Creating a Report from a Structured Log File:**

```cpp
#include <sstream>
#include <map>
#include <vector>
using namespace std;

ifstream infile("log.txt");
map<string, vector<string>> errors;
string line;

while (getline(infile, line))
{
  istringstream mystream(line);
  string timestamp, level, message;

  mystream >> timestamp >> level >> message;
  errors[level].push_back(message);
}

ostringstream mystream;
mystream << "Error Report:" << endl;
for (const auto& kv : errors)
{
  mystream << "Level: " << kv.first << endl;
  for (const auto& msg : kv.second)
  {
    mystream << "\t" << msg << endl;
  }
}
```

**22. Parsing a URL:**

```cpp
#include <sstream>
#include <boost/algorithm/string.hpp>
using namespace std;

istringstream mystream("https://www.example.com/path/to/file?param1=value1&param2=value2");
string scheme, host, path, query_string;

// Extract scheme
mystream.ignore(6);
getline(mystream, scheme, ':');

// Extract host
mystream.ignore(2);
getline(mystream, host, '/');

// Extract path
string tmp;
getline(mystream, tmp, '/');
while (tmp != "")
{
  path += '/' + tmp;
  getline(mystream, tmp, '/');
}

// Extract query string
if (mystream.peek() == '?')
{
  mystream.ignore();
  getline(mystream, query_string);
}

// Parse query string
map<string, string> query_params;
vector<string> pairs;
boost::split(pairs, query_string, boost::is_any_of("&"));
for (const auto& pair : pairs)
{
  vector<string> key_value;
  boost::split(key_value, pair, boost::is_any_of("="));
  query_params[key_value[0]] = key_value[1];
}
```

**23. Generating Random Data:**

```cpp
#include <sstream>
#include <random>
using namespace std;

random_device rd;
mt19937 gen(rd());
uniform_int_distribution<int> dist(0, 9);

ostringstream mystream;
for (int i = 0; i < 10; i++)
{
  mystream << dist(gen);
}
```

**24. Encrypting and Decrypting a String:**

```cpp
#include <sstream>
#include <cryptopp/cryptlib.h>
#include <cryptopp/hex.h>
#include <cryptopp/aes.h>
using namespace CryptoPP;

string encrypt(const string& plaintext, const string& key)
{
  AES::Encryption aes(key.data(), key.size());
  string ciphertext;
  StringSource ss(plaintext, true,
                  new StreamTransformationFilter(aes, new StringSink(ciphertext)));
  return ciphertext;
}

string decrypt(const string& ciphertext, const string& key)
{
  AES::Decryption aes(key.data(), key.size());
  string plaintext;
  StringSource ss(ciphertext, true,
                  new StreamTransformationFilter(aes, new StringSink(plaintext)));
  return plaintext;
}

int main()
{
  string plaintext = "Hello World";
  string key = "my_secret_key";
  ostringstream mystream;

  mystream << "Encrypted: " << HexEncoder().Encode(encrypt(plaintext, key));
  mystream << "\nDecrypted: " << decrypt(mystream.str().substr(13), key);
}
```

**25. Counting Occurrences of a Character in a String:**

```cpp
#include <sstream>
#include <map>
using namespace std;

ostringstream mystream;
string str = "Hello World";

// Create a map to store the character counts
map<char, int> char_counts;

// Iterate over the string and count the characters
for (char c : str)
{
  char_counts[c]++;
}

// Iterate over the map and add the results to the string stream
for (const auto& kv : char_counts)
{
  mystream << kv.first << ": " << kv.second << endl;
}
```

**26. Creating a CSV File with Header:**

```cpp
#include <sstream>
#include <fstream>
using namespace std;

ofstream csv_file("output.csv");

// Create a string stream for the header
ostringstream header;

// Add header fields to the stream
header << "Name,Age,City" << endl;

// Write the header to the CSV file
csv_file << header.str();
```

**27. Serializing a Custom Object to a String:**

```cpp
#include <sstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
using namespace std;

struct Person
{
  string name;
  int age;

  Person(const string& name, int age) : name(name), age(age) {}

  friend class boost::serialization::access;
  template<class Archive>
  void serialize(Archive& ar, const unsigned int version)
  {
    ar & name & age;
  }
};

int main()
{
  Person john("John", 30);
  ostringstream mystream;
  boost::archive::text_oarchive archive(mystream);
  archive << john;
}
```

**28. Deserializing a Custom Object from a String:**

```cpp
#include <sstream>
#include <boost/archive/text_oarchive.hpp>
#include <boost/archive/text_iarchive.hpp>
using namespace std;

struct Person
{
  string name;
  int age;

  Person(const string& name, int age) : name(name), age(age) {}

  friend class boost::serialization::access;
  template<class Archive>
  void serialize(Archive& ar, const unsigned int version)
  {
    ar & name & age;
  }
};

int main()
{
  string serialized_person = "John,30";
  istringstream mystream(serialized_person);
  boost::archive::text_iarchive archive(mystream);
  Person john;
  archive >> john;
}
```

**29. Tokenizing a String with Custom Delimiters:**

```cpp
#include <sstream>
#include <vector>
using namespace std;

vector<string> tokenize(const string& str, const string& delimiters)
{
  istringstream mystream(str);
  vector<string> tokens;
  string token;

  while (getline(mystream, token, delimiters[0]))
  {
    for (size_t i = 1; i < delimiters.size(); i++)
    {
      getline(mystream, token, delimiters[i]);
    }
    tokens.push_back(token);
  }

  return tokens;
}
```

**30. Counting the Number of Lines in a String:**

```cpp
#include <sstream>
#include <string>
using namespace std;

int count_lines(const string& str)
{
  istringstream mystream(str);
  int line_count = 0;

  while (mystream.peek() != EOF)
  {
    string line;
    getline(mystream, line);
    line_count++;
  }

  return line_count;
}
```

**31. Creating a Histogram from a Data File:**

```cpp
#include <sstream>
#include <map>
using namespace std;

ifstream infile("data.txt");
map<int, int> histogram;
int num;

while (infile >> num)
{
  histogram[num]++;
}

ostringstream mystream;
mystream << "Histogram:" << endl;
for (const auto& kv : histogram)
{
  mystream << kv.first << ": " << string(kv.second, '*') << endl;
}
```

**32. Parsing a Log File for Errors:**

```cpp
#include <sstream>
#include <vector>
using namespace std;

ifstream infile("log.txt");
vector<string> errors;
string line;

while (getline(infile, line))
{
  istringstream mystream(line);
  string level, message;

  mystream >> level >> message;
  if (level == "ERROR")
  {
    errors.push_back(message);
  }
}
```

**33. Creating a Markdown Document from HTML:**

```cpp
#include <sstream>
#include <boost/algorithm/string.hpp>
using namespace std;

string convert_html_to_markdown(const string& html)
{
  istringstream mystream(html);
  ostringstream markdown;
  string line;

  while (getline(mystream, line))
  {
    boost::replace_all(line, "<h1>", "## ");
    boost::replace_all(line, "<h2>", "### ");
    boost::replace_all(line, "<h3>", "#### ");
    boost::replace_all(line, "<strong>", "**");
    boost::replace_all(line, "</strong>", "**");
    boost::replace_all(line, "<p>", "");
    boost::replace_all(line, "</p>", "");
    boost::replace_all(line, "<br>", "");
    markdown << line << endl;
  }

  return markdown.str();
}
```

**34. Parsing a Command-Line Interface (CLI) Argument:**

```cpp
#include <sstream>
#include <vector>
using namespace std;

int main(int argc, char* argv[])
{
  if (argc < 2)
  {
    cout << "Error: Missing argument" << endl;
    return 1;
  }

  istringstream mystream(argv[1]);
  int arg_value;
  mystream >> arg_value;
  cout << "Argument value: " << arg_value << endl;

  return 0;
}
```

**35. Creating a JSON Patch from an Object:**

```cpp
#include <sstream>
#include <nlohmann/json.hpp>
using namespace std;

nlohmann::json to_json_patch(const nlohmann::json& old_obj, const nlohmann::json& new_obj)
{
  nlohmann::json patch;

  for (const auto& [key, value] : new_obj.items())
  {
    if (value != old_obj[key])
    {
      patch.push_back({{"op", "replace"}, {"path", "/" + key}, {"value", value}});
    }
  }

  return patch;
}
```

**36. Removing Duplicate Lines from a Text File:**

```cpp
#include <sstream>
#include <set>
using namespace std;

ifstream infile("input.txt");
ofstream outfile("output.txt");
set<string> unique_lines;
string line;

while (getline(infile, line))
{
  if (unique_lines.find(line) == unique_lines.end())
  {
    unique_lines.insert(line);
    outfile << line << endl;
  }
}
```

**37. Generating a Random Password:**

```cpp
#include <sstream>
#include <random>
using namespace std;

string generate_password(int length)
{
  ostringstream mystream;
  random_device rd;
  mt19937 gen(rd());
  uniform_int_distribution<int> dist('!', '~');

  for (int i = 0; i < length; i++)
  {
    mystream << static_cast<char>(dist(gen));
  }

  return mystream.str();
}
```

**38. Creating a Color Palette from a Hex Code:**

```cpp
#include <sstream>
#include <iomanip>
using namespace std;

vector<string> create_palette(const string& hex_code)
{
  vector<string> palette;

  // Convert hex code to integer
  int color_value = stoul(hex_code.substr(1), nullptr, 16);

  // Generate shades by decreasing red, green, and blue values
  for (int i = 0; i < 10; i++)
  {
    int red = (color_value >> 16) - i * 25;
    int green = ((color_value >> 8) & 0xFF) - i * 25;
    int blue = (color_value & 0xFF) - i * 25;

    // Convert back to hex code
    ostringstream mystream;
    mystream << "#" << setfill('0') << setw(2) << hex << red << setw(2) << hex << green << setw(2) << hex << blue;
    palette.push_back(mystream.str());
  }

  return palette;
}
```

**39. Parsing and Converting Numbers from a String:**

```cpp
#include <sstream>
#include <vector>
using namespace std;

vector<int> parse_numbers(const string& str)
{
  istringstream mystream(str);
  vector<int> numbers;
  int num;

  while (mystream >> num)
  {
    numbers.push_back(num);
  }

  return numbers;
}
```

**40. Creating a CSV File with Headers and Line Breaks:**

```cpp
#include <sstream>
#include <fstream>
using namespace std;

ofstream csv_file("output.csv");

// Create a string stream for the header
ostringstream header;

// Add header fields to the stream
header << "Name,Age,City" << endl;

// Write the header to the CSV file
csv_file << header.str();

// Create a string stream for the data rows
ostringstream rows;

// Add data rows to the stream
rows << "John,30,New York" << endl;
rows << "Jane,25,London" << endl;

// Write the data rows to the CSV file
csv_file << rows.str();
```

**41. Creating a Tab-Separated File:**

```cpp
#include <sstream>
#include <fstream>
using namespace std;

ofstream tsv_file("output.tsv");

// Create a string stream for the header
ostringstream header;

// Add header fields to the stream, separated by tabs
header << "Name\tAge\tCity" << endl;

// Write the header to the TSV file
tsv_file << header.str();

// Create a string stream for the data rows
ostringstream rows;

// Add data rows to the stream, separated by tabs
rows << "John\t30\tNew York" << endl;
rows << "Jane\t25\tLondon" << endl;

// Write the data rows to the TSV file
tsv_file << rows.str();
```

**42. Converting a String to UPPERCASE:**

```cpp
#include <sstream>
#include <locale>
using namespace std;

ostringstream mystream;

// Convert a string to uppercase
mystream << "hello world" << std::uppercase;
```

**43. Converting a String to LOWERCASE:**

```cpp
#include <sstream>
#include <locale>
using namespace std;

ostringstream mystream;

// Convert a string to lowercase
mystream << "HELLO WORLD" << std::lowercase;
```

**44. Generating a Random Number:**

```cpp
#include <sstream>
#include <random>
using namespace std;

ostringstream mystream;

// Generate a random number between 0 and 99
mystream << rand() % 100;
```

**45. Calculating the Sum of Numbers from a String:**

```cpp
#include <sstream>
#include <vector>
using namespace std;

ostringstream mystream;

// Calculate the sum of numbers from a string
istringstream mystream("1 2 3 4 5");
int sum = 0;
int num;

while (mystream >> num)
{
  sum += num;
}

mystream << "Sum: " << sum;
```

**46. Extracting Words from a String:**

```cpp
#include <sstream>
#include <vector>
using namespace std;

ostringstream mystream;

// Extract words from a string
string str = "Hello World This is a test";
istringstream mystream(str);
vector<string> words;
string word;

while (mystream >> word)
{
  words.push_back(word);
}
```

**47. Converting an Integer to a String:**

```cpp
#include <sstream>
using namespace std;

ostringstream mystream;

// Convert an integer to a string
int num = 12345;
mystream << num;
```

**48. Reversing a String:**

```cpp
#include <sstream>
#include <algorithm>
using namespace std;

ostringstream mystream;

// Reverse a string
string str = "Hello World";
reverse(str.begin(), str.end());
mystream << str;
```

**49. Combining Multiple Strings into One:**

```cpp
#include <sstream>
using namespace std;

ostringstream mystream;

// Combine multiple strings into one
string str1 = "Hello";
string str2 = "World";
string str3 = "This";
string str4 = "is";
string str5 = "a";
string str6 = "test";

mystream << str1 << " " << str2 << " " << str3 << " " << str4 << " " << str5 << " " << str6;
```

**50. Splitting a String Based on a Delimiter:**

```cpp
#include <sstream>
#include <vector>
using namespace std;

ostringstream mystream;

// Split a string based on a delimiter
string str = "Hello,World,This,is,a,test";
vector<string> tokens;
string token;

istringstream mystream(str);
while (getline(mystream, token, ','))
{
  tokens.push_back(token);
}
```
