What is a good, safe way to extract a specific number of characters from a std::basic_istream
and store it in a std::string
?
In the following program I use a char[]
to eventually obtain result
, but I would like to avoid the POD types and ensure something safer and more maintainable:
#include <sstream>
#include <string>
#include <iostream>
#include <exception>
int main()
{
std::stringstream inss{std::string{R"(some/path/to/a/file/is/stored/in/50/chars Other data starts here.)"}};
char arr[50]{};
if (!inss.read(arr,50))
throw std::runtime_error("Could not read enough characters.\n");
//std::string result{arr}; // Will probably copy past the end of arr
std::string result{arr,arr+50};
std::cout << "Path is: " << result << '\n';
std::cout << "stringstream still has: " << inss.str() << '\n';
return 0;
}
Alternatives:
- Convert entire stream to a string up front:
std::string{inss.c_str()}
- This seems wasteful as it would make a copy of the entire stream.
- Write a template function to accept the
char[]
- This would still use an intermediate POD array.
- Use
std::basic_istream::get
in a loop to read the required number of characters together withstd::basic_string::push_back
- The loop seems a bit unwieldy, but it does avoid the array.