C++中如何将从文件读取的数组复制到另一个文件?
解决C++数组复制到文件时的垃圾值与格式问题
你遇到的问题主要来自两个核心点:错误的复制范围和缺少输出分隔符,咱们一步步拆解解决:
1. 垃圾值的来源
你用sizeof(numbers)来计算数组的复制结尾,但sizeof(numbers)返回的是整个数组的字节大小(比如int占4字节时,5个元素的数组就是20字节),numbers + sizeof(numbers)会直接超出数组中有效元素的范围,把数组后面未初始化的内存垃圾数据也写入了文件,这就是那些乱码数字的由来。
而你实际只从文件里读取了count个有效元素(也就是4个),所以复制范围应该是numbers到numbers + count,而非整个数组。
2. 数字连在一起的原因
ostream_iterator<int>默认会直接连续输出整数,不会添加任何分隔符,所以10、20这些数字会被拼写成10203040。你可以在构造ostream_iterator时指定分隔符,比如空格或者换行。
修改后的写入代码片段
把你添加的写入代码改成这样:
ofstream fstreamFile("destination.txt"); // 用count限定有效元素范围,同时指定空格作为分隔符 copy(numbers, numbers + count, ostream_iterator<int>(fstreamFile, " ")); fstreamFile.close(); // 手动关闭文件确保数据完全写入
完整的修改后程序示例
整合到原有代码里,完整的main函数如下(注意补充必要的头文件):
#include <iostream> #include <fstream> #include <algorithm> // copy函数需要的头文件 #include <iterator> // ostream_iterator需要的头文件 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; // 优化后的写入文件逻辑 ofstream fstreamFile("destination.txt"); if (!fstreamFile) { // 增加文件打开检查,避免静默失败 cout << "error opening output file\n"; return 1; } copy(numbers, numbers + count, ostream_iterator<int>(fstreamFile, " ")); fstreamFile.close(); cout << "5. Program ending" << endl; return 0; }
额外提醒
- 必须包含
<algorithm>和<iterator>头文件,否则copy函数和ostream_iterator会编译报错。 - 增加输出文件的打开检查,可以及时发现权限不足、路径错误等问题,避免写入失败却毫无察觉。
内容的提问来源于stack exchange,提问作者hbakan
相关产品推荐
相关产品推荐

