C++ 如何将数组复制到c++;
我从文本文件中读取数组,并希望将此数组的元素复制到另一个文本文件中C++ 如何将数组复制到c++;,c++,arrays,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";
#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;
}
#包括
#包括
使用名称空间std;
int main()
{
常量int数组_SIZE=5;
整数[数组大小];
整数计数=0;
cout问题是您使用sizeof
作为数组的结尾“迭代器”
sizeof
运算符返回的大小以字节为单位,而不是以数组元素为单位。这意味着您将超出数组末尾的范围
我建议您改为使用标准和帮助函数来获取数组的“迭代器”:
std::copy(std::begin(numbers), std::end(numbers), ...);
为适当的数组(但不是指针,记住数组很容易衰减指针),这些函数将做正确的事情。
谢谢,它解决了我的问题。@ HBAKAN如果它做了,然后把它标记为“接受”。
std::copy(std::begin(numbers), std::end(numbers), ...);