如何在c ++中将数组复制到文件中

时间:2018-01-03 12:57:52

标签: c++ arrays

我从文本文件中读取数组,我想将此数组的元素复制到另一个文本文件

#include <iostream>
#include <fstream>


using namespace std;

int main()

{

    const int ARRAY_SIZE = 5;
    int numbers[ ARRAY_SIZE];
    int count = 0;
    cout << "1. before opening file\n";

    ifstream inputFile;
    inputFile.open("test.txt");    

    if (!inputFile)
    {
        cout << "error opening input file\n";
        return 1;
    }

    cout << "2. after opening file\n";
    cout << "3. before reading file, count = " << count << '\n';

    while (count < ARRAY_SIZE && inputFile >> numbers [ count])
        count++;

    inputFile.close();

    cout << "4. after reading file, count = " << count << '\n';
    cout<< "The numbers are : ";

    for (int i = 0; i < count; i++)

        cout << numbers[i] << " ";
    cout<< endl;

    cout << "5. Program ending" << endl;
    return 0;

}

我添加了此代码,但它不起作用。如何将此数组的元素复制到destination.txt文件?

ofstream fstreamFile("destination.txt");
    copy(
         numbers,
         numbers + sizeof(numbers),
         ostream_iterator<int>(fstreamFile)
         );

我的元素是10,20,30,40但是在destination.txt文件中,输出是“10203040160641613632767-1973944304 -....”

1 个答案:

答案 0 :(得分:2)

问题是您使用sizeof作为数组的结尾“迭代器”。

sizeof运算符返回字节 中的大小,而不是数组元素。这意味着你将超越数组的末尾。

我建议您更改为使用标准std::beginstd::end辅助函数来获取数组的“迭代器”:

std::copy(std::begin(numbers), std::end(numbers), ...);

对于正确的数组(但不是指针,并记住数组很容易衰减指针)这些函数将做正确的事。