Skip to content

Instantly share code, notes, and snippets.

@ducalpha
Last active May 6, 2016 18:44
Show Gist options
  • Save ducalpha/65ef734f967713e04aa29c5d61920e86 to your computer and use it in GitHub Desktop.
Save ducalpha/65ef734f967713e04aa29c5d61920e86 to your computer and use it in GitHub Desktop.
Using input/output string streams for dynamic reading
// Example program
#include <iostream>
#include <string>
#include <sstream>
#include <vector>
#include <exception>
using namespace std;
int main()
{
ostringstream output;
try {
output.exceptions(std::ios_base::failbit | std::ios_base::badbit);
int a_int = 1;
int a_bool = false;
vector<string> a{"test", "test2"};
output << a_int << endl;
output << a.size() << endl;
output << a[0] << endl;
output << a[1] << endl;
output << a_bool << endl;
cout << output.str() << endl;
} catch (const std::ios_base::failure& e) {
std::cout << "Exception writing\n";
return 1;
}
try {
istringstream input(output.str());
input.exceptions(std::ios_base::failbit | std::ios_base::badbit);
int b_int;
size_t b_size;
vector<string> b;
bool b_bool;
input >> b_int;
cout << b_int << endl;
input >> b_size;
cout << b_size << endl;
b.resize(b_size);
int test_exception;
input >> test_exception; // exception here
for (size_t i = 0; i < b_size; ++i) {
string tmp;
input >> tmp;
b[i] = tmp;
cout << tmp << endl;
}
input >> b_bool;
cout << b_bool;
} catch (const std::ios_base::failure& e) {
std::cout << "Exception reading: " << e.what();
return 1;
}
return 0;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment