How would i output my vector of strings into a ".txt" file?

Recommended Answers

All 3 Replies

The same way you would write any character array. If you don't know how to do that either here is a tutorial to help you out.

You have to iterate through the elements of the vector and output each string to the file.

Here's one way:

std::ofstream file_out("filename.txt");
std::copy(v.begin(), v.end(),
          std::ostream_iterator<std::string>(file_out, "\n"));

Here's another:

std::ofstream file_out("filename.txt");
for(const auto& s : v)
  file_out << s << std::endl;

Here's another:

std::ofstream file_out("filename.txt");
for(auto it = v.begin(); it != v.end(); ++it)
  file_out << *it << std::endl;

Here's another:

std::ofstream file_out("filename.txt");
for(std::size_t i = 0; i < v.size(); ++i)
  file_out << v[i] << std::endl;

There's really not much to it. Pick what you are most comfortable with.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.