简体   繁体   中英

Reading/writing C++ vector to a file

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/

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";
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM