简体   繁体   English

读/写 C++ 向量到一个文件

[英]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/ 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.打开 output 文件并检查是否有效。
  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.迭代可以通过使用迭代器、索引运算符[] 、基于范围的 for 循环或算法库中的许多算法等来完成。

Easiest solution seems to be the usage of a range based for loop:最简单的解决方案似乎是使用基于范围的 for 循环:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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