# iostream

***

**1. Reading and Writing to Standard Input and Output**

```cpp
int main() {
  int x;
  // Read integer from standard input
  cin >> x;
  // Write integer to standard output
  cout << x << endl;
}
```

**2. Accepting Multiple Input Values**

```cpp
int main() {
  int a, b, c;
  // Read three integers from standard input
  cin >> a >> b >> c;
  // Do something with the values
  // ...
}
```

**3. Writing Formatting Output**

```cpp
int main() {
  int x = 1234;
  // Write formatted output to standard output
  cout << "The number is: " << x << endl;
}
```

**4. Reading Input from a File**

```cpp
int main() {
  ifstream input("input.txt");
  int x;
  // Read integer from file
  input >> x;
  // Do something with the value
  // ...
}
```

**5. Writing Output to a File**

```cpp
int main() {
  ofstream output("output.txt");
  int x = 1234;
  // Write integer to file
  output << x << endl;
}
```

**6. Redirecting Input and Output**

```cpp
int main() {
  // Redirect standard input from "input.txt"
  freopen("input.txt", "r", stdin);
  // Redirect standard output to "output.txt"
  freopen("output.txt", "w", stdout);
  // ...
}
```

**7. Buffering Output**

```cpp
int main() {
  // Flush output buffer immediately
  cout.flush();
}
```

**8. Reading a Line of Text**

```cpp
int main() {
  string line;
  // Read line of text from standard input
  getline(cin, line);
  // Do something with the line
  // ...
}
```

**9. Reading and Writing Binary Data**

```cpp
int main() {
  ifstream input("binary.bin", ios::binary);
  ofstream output("binary2.bin", ios::binary);
  int x = 1234;
  // Read integer from binary file
  input.read((char*)&x, sizeof(x));
  // Write integer to binary file
  output.write((char*)&x, sizeof(x));
}
```

**10. Manipulating File Pointers**

```cpp
int main() {
  ifstream input("file.txt");
  // Get current file position
  streampos pos = input.tellg();
  // Move file pointer to beginning
  input.seekg(0, ios::beg);
  // ...
}
```

**11. Error Handling**

```cpp
int main() {
  ifstream input("file.txt");
  if (input.fail()) {
    // Error occurred
    cerr << "Error opening file" << endl;
  } else {
    // ...
  }
}
```

**12. Reading Input from a String**

```cpp
int main() {
  string input = "1234";
  istringstream stream(input);
  int x;
  // Read integer from string
  stream >> x;
  // ...
}
```

**13. Writing Output to a String**

```cpp
int main() {
  ostringstream stream;
  int x = 1234;
  // Write integer to string stream
  stream << x;
  string output = stream.str();
  // ...
}
```

**14. Using I/O Manipulators**

```cpp
int main() {
  int x = 1234;
  // Set output precision to 2 decimal places
  cout << fixed << setprecision(2);
  // Write formatted output to standard output
  cout << "The number is: " << x << endl;
}
```

**15. Using Locale-Specific Formatting**

```cpp
int main() {
  int x = 1234;
  // Set locale-specific formatting
  cout.imbue(std::locale(""));
  // Write formatted output to standard output
  cout << "The number is: " << x << endl;
}
```

**16. Using Custom Stream Buffers**

```cpp
class MyStreamBuffer : public streambuf {
public:
  // ...
};

int main() {
  MyStreamBuffer myStreamBuffer;
  streambuf* oldStreamBuffer = cout.rdbuf();
  // Set custom stream buffer for standard output
  cout.rdbuf(&myStreamBuffer);
  // ...
  // Restore old stream buffer
  cout.rdbuf(oldStreamBuffer);
}
```

**17. Using Custom Stream Manipulators**

```cpp
ostream& myManipulator(ostream& out) {
  // ...
  return out;
}

int main() {
  int x = 1234;
  // Use custom stream manipulator
  cout << myManipulator << x << endl;
}
```

**18. Using Input and Output Iterators**

```cpp
int main() {
  vector<int> numbers = {1, 2, 3, 4, 5};
  // Read from vector using input iterator
  copy(istream_iterator<int>(cin), istream_iterator<int>(), numbers.begin());
  // Write to vector using output iterator
  copy(numbers.begin(), numbers.end(), ostream_iterator<int>(cout, " "));
}
```

**19. Reading from a Compressed File**

```cpp
int main() {
  // Create a compressed file stream
  ifstream input("file.gz");
  input.seekg(0, ios::beg);
  gzifstream gzInput(input);
  // Read from compressed file
  // ...
}
```

**20. Writing to a Compressed File**

```cpp
int main() {
  // Create a compressed file stream
  ofstream output("file.gz");
  output.seekp(0, ios::beg);
  gzofstream gzOutput(output);
  // Write to compressed file
  // ...
}
```

**21. Using Memory Streams**

```cpp
int main() {
  // Create memory stream
  stringstream stream;
  // Write to memory stream
  stream << "Hello world" << endl;
  // Read from memory stream
  string line;
  getline(stream, line);
  // ...
}
```

**22. Using String Streams**

```cpp
int main() {
  // Create string stream
  stringstream stream("Hello world");
  // Read from string stream
  string line;
  getline(stream, line);
  // ...
}
```

**23. Reading and Writing Unicode Characters**

```cpp
int main() {
  // Read Unicode character from standard input
  wchar_t wchar;
  wcin >> wchar;
  // Write Unicode character to standard output
  wcout << wchar << endl;
}
```

**24. Parsing JSON Data**

```cpp
int main() {
  json data;
  // Read JSON data from standard input
  cin >> data;
  // Parse JSON data
  // ...
}
```

**25. Writing XML Data**

```cpp
int main() {
  xml_document doc;
  // Create XML document
  // ...
  // Write XML document to standard output
  cout << doc;
}
```

**26. Reading and Writing Binary Data with Boost Serialization**

```cpp
int main() {
  ofstream output("file.bin");
  boost::archive::text_oarchive oa(output);
  int x = 1234;
  // Serialize integer
  oa << x;
}
```

**27. Reading and Writing Binary Data with Qt Serialization**

```cpp
int main() {
  QFile file("file.bin");
  file.open(QIODevice::WriteOnly);
  QDataStream out(&file);
  int x = 1234;
  // Serialize integer
  out << x;
}
```

**28. Reading and Writing Data with Protocol Buffers**

```cpp
int main() {
  MyMessage message;
  // Set message fields
  message.set_field1(1234);
  // Serialize message
  string serializedMessage;
  message.SerializeToString(&serializedMessage);
  // Deserialize message
  MyMessage parsedMessage;
  parsedMessage.ParseFromString(serializedMessage);
}
```

**29. Using I/O with Network Sockets**

```cpp
int main() {
  // Create socket
  SOCKET socket = socket(AF_INET, SOCK_STREAM, 0);
  // Bind socket to address
  bind(socket, (sockaddr*)&address, sizeof(address));
  // Listen for incoming connections
  listen(socket, 5);
  // Accept incoming connection
  SOCKET clientSocket = accept(socket, (sockaddr*)&clientAddr, &addrlen);
  // Send data to client
  send(clientSocket, data, strlen(data), 0);
  // Receive data from client
  recv(clientSocket, buffer, sizeof(buffer), 0);
}
```

**30. Using I/O with Filesystem Operations**

```cpp
int main() {
  // Create directory
  mkdir("myDirectory", S_IRWXU | S_IRWXG | S_IROTH);
  // Remove directory
  rmdir("myDirectory");
  // Create file
  ofstream output("myfile.txt");
  // Write to file
  // ...
}
```

**31. Using I/O with Compression Libraries**

```cpp
int main() {
  // Compress data
  string compressedData = compress(data);
  // Decompress data
  string decompressedData = decompress(compressedData);
}
```

**32. Using I/O with Encryption Libraries**

```cpp
int main() {
  // Encrypt data
  string encryptedData = encrypt(data);
  // Decrypt data
  string decryptedData = decrypt(encryptedData);
}
```

**33. Using I/O with Logging Libraries**

```cpp
int main() {
  // Initialize logging library
  initLogging("myApplication.log");
  // Log message
  LOG_INFO("Hello world");
}
```

**34. Using I/O with Database Libraries**

```cpp
int main() {
  // Connect to database
  Connection connection("user", "password", "myDatabase");
  // Execute query
  ResultSet results = connection.execute("SELECT * FROM myTable");
  // Iterate through results
  // ...
}
```

**35. Using I/O with HTTP Libraries**

```cpp
int main() {
  // Create HTTP client
  HttpClient client("example.com");
  // Send HTTP request
  HttpResponse response = client.get("/index.html");
  // Read HTTP response
  string body = response.getBody();
}
```

**36. Using I/O with XML Parsers**

```cpp
int main() {
  // Create XML parser
  XMLParser parser;
  // Parse XML document
  parser.parse("myDocument.xml");
  // Get root element
  XMLElement* root = parser.getRootElement();
  // Iterate through child elements
  // ...
}
```

**37. Using I/O with JSON Parsers**

```cpp
int main() {
  // Create JSON parser
  JSONParser parser;
  // Parse JSON document
  JSONValue json = parser.parse("myDocument.json");
  // Get object value
  JSONObject object = json.asObject();
  // Iterate through object keys
  // ...
}
```

**38. Using I/O with CSV Parsers**

```cpp
int main() {
  // Create CSV parser
  CSVParser parser;
  // Parse CSV document
  CSVData data = parser.parse("myDocument.csv");
  // Get row count
  int rowCount = data.rowCount();
  // Get column count
  int columnCount = data.columnCount();
  // Iterate through rows and columns
  // ...
}
```

**39. Using I/O with Regex Libraries**

```cpp
int main() {
  // Create regex object
  Regex regex("[a-zA-Z0-9]+");
  // Search for matches
  string text = "Hello world 123";
  vector<string> matches = regex.findAll(text);
}
```

**40. Using I/O with Data Structures**

```cpp
int main() {
  // Create vector
  vector<int> numbers = {1, 2, 3, 4, 5};
  // Iterate through vector using I/O iterators
  copy(numbers.begin(), numbers.end(), ostream_iterator<int>(cout, " "));
}
```

**41. Using I/O with Algorithms**

```cpp
int main() {
  // Create vector
  vector<int> numbers = {1, 2, 3, 4, 5};
  // Find maximum value
  int max = *max_element(numbers.begin(), numbers.end());
  // Print maximum value
  cout << "Maximum value: " << max << endl;
}
```

**42. Using I/O with Preprocessor Macros**

```cpp
#define PRINT_LINE cout << "-------------------------" << endl;

int main() {
  // Print line
  PRINT_LINE;
}
```

**43. Using I/O with Assertions**

```cpp
int main() {
  // Assert condition
  assert(x > 0);
  // Print error message if assertion fails
  cout << "Assertion failed: x is not greater than 0" << endl;
}
```

**44. Using I/O with Error Handling**

```cpp
int main() {
  try {
    // Open file
    ifstream input("file.txt");
    // Read from file
    // ...
  } catch (ifstream::failure& e) {
    // Handle file open failure
    cout << "Error opening file: " << e.what() << endl;
  }
}
```

**45. Using I/O with Lambdas**

```cpp
int main() {
  // Create lambda function for output
  auto outputFunc = [](int x) { cout << x << endl; };
  // Invoke lambda function
  outputFunc(1234);
}
```

**46. Using I/O with Scoped Variables**

```cpp
int main() {
  // Create scoped variable for output
  ofstream output("file.txt");
  {
    // Use scoped variable
    output << "Hello world" << endl;
  }
  // Scoped variable is automatically closed
}
```

**47. Using I/O with Threading**

```cpp
int main() {
  // Create thread for output
  thread outputThread([]() { cout << "Hello world" << endl; });
  // Join thread
  outputThread.join();
}
```

**48. Using I/O with Shared Memory**

```cpp
int main() {
  // Create shared memory object
  shared_memory_object sharedMemory("mySharedMemory");
  // Map shared memory to process memory
  void* sharedData = sharedMemory.map(sizeof(int));
  // Write to shared memory
  int x = 1234;
  memcpy(sharedData, &x, sizeof(int));
  // Unmap shared memory from process memory
  sharedMemory.unmap(sharedData);
}
```

**49. Using I/O with Semaphores**

```cpp
int main() {
  // Create semaphore object
  semaphore semaphore("mySemaphore");
  // Acquire semaphore
  semaphore.acquire();
  // Critical section
  // ...
  // Release semaphore
  semaphore.release();
}
```

**50. Using I/O with Mutexes**

```cpp
int main() {
  // Create mutex object
  mutex mutex;
  // Lock mutex
  mutex.lock();
  // Critical section
  // ...
  // Unlock mutex
  mutex.unlock();
}
```
