Home > Enterprise >  c using std::copy to copy an istream to a char* buffer
c using std::copy to copy an istream to a char* buffer

Time:04-17

Is there a way to copy a std::istream to a buffer of data accessed by a "data()" method which returns a char*? For instance, the below code example. It results in a segfault. I know I could use std::back_inserter in this example, but my goal is not to copy to a vector ultimately.

#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
int main() {
  std::vector<char> vec;
  std::istringstream ss("foobar");
  std::copy(std::istream_iterator<char>(ss), std::istream_iterator<char> 
  (),vec.data());
}

CodePudding user response:

No problem to copy provided enough storage is allocated upfront:

#include <sstream>
#include <algorithm>
#include <iterator>
#include <vector>
int main()
{
  std::vector<char> vec(6); //note what happens here!
  std::istringstream ss("foobar");
  std::copy(std::istream_iterator<char>(ss), std::istream_iterator<char> 
  (), vec.data());
}
  • Related