0

I want to store vector to a file and read it line by line for each vector.

vector<int> vec1 = {1,1,0,1};
vector<int> vec2 = {1,0,0,1,1,1};
vector<int> vec3 = {1,1,0};
...
data.txt
1 1 0 1
1 0 0 1 1 1
1 1 0
...

I read this page and still confused. http://www.cplusplus.com/forum/general/165809/

  • 1
    Do you know how to iterate over (loop over) a vector? For example to print its values on `std::cout`? Then you really know how to write to a file as well, as it's done in the exact same way. The `std::cout` object is an *output stream*, and `std::ofstream` is an *output file stream*. – Some programmer dude May 08 '22 at 09:25
  • 1
    I also recommend you to invest in [some good C++ books](https://stackoverflow.com/questions/388242/the-definitive-c-book-guide-and-list/388282#388282), as they are better to learn from than using reference sites and online tutorials where the quality is unknown. – Some programmer dude May 08 '22 at 09:26

1 Answers1

0

Let me shortly help you.

What you need to do is:

  1. Open the output file and check, if that works.
  2. Then for each vector, iterate over all elements and write them to the file

Iterating can be done by using iterators, the index operator [], with a range based for loop or with many algorithms from the algorithm library, or more.

Easiest solution seems to be the usage of a range based for loop:

#include <iostream>
#include <fstream>
#include <vector>

int main() {

    // Definition of source data
    std::vector<int> vec1 = { 1,1,0,1 };
    std::vector<int> vec2 = { 1,0,0,1,1,1 };
    std::vector<int> vec3 = { 1,1,0 };

    // Open file
    std::ofstream fileStream("data.txt");

    // Check, if file could be opened
    if (fileStream) {

        // Write all data from vector 1
        for (int i1 : vec1) fileStream << i1 << ' ';
        fileStream << '\n';
        // Write all data from vector 2
        for (int i2 : vec2) fileStream << i2 << ' ';
        fileStream << '\n';
        // Write all data from vector 3
        for (int i3 : vec3) fileStream << i3 << ' ';
        fileStream << std::endl;
    }
    else {
        // File could not be opened. Show error message
        std::cerr << "\n***Error: Could not open output file\n";
    }
}
A M
  • 14,694
  • 5
  • 19
  • 44