在组合两个数组并计算其大小后打印一个新的数组



任务是将第一个数组和第二个数组的内容复制到第三个数组中并显示。当我尝试这个时,我得到了垃圾值。我做错了什么?谢谢。

  • input1.txt=你好
  • input2.txt=今天先生
#include <iostream>
#include <fstream>
using namespace std; 
void display(char* ptr, int size)
{ 
for (int i = 0; i < size; i++)
{ 
cout << ptr[i]<< " "; 
} 
cout << endl; 
}
int main() 
{ 
ifstream fin1; 
fin1.open("input1.txt"); 
int size1 = 0; 
while (!fin1.eof()) 
{
fin1.get(); size1++; 
} 
char* arr1 = new char[size1]; 
fin1.close(); 
fin1.open("input1.txt"); 
fin1.getline(arr1, size1); 
ifstream fin2; 
fin2.open("input2.txt"); 
int size2 = 0; 

while (!fin2.eof())
{ 
fin2.get(); size2++; 
} 
char* arr2 = new char[size2]; 
fin2.close(); 
fin2.open("input2.txt"); 
fin2.getline(arr2, size2); 
int size3 = size1 + size2; 
char* arr3 = new char[size3 + 2]; 
return 0; 
}

根据赋值的措辞,这可能在法律上是正确的。它只使用您当前使用的两个标头。没有std::string或任何"花哨的东西";一般不允许。

#include <iostream>
#include <fstream>
int main()
{
// open the files
std::ifstream fin1("input1.txt");
std::ifstream fin2("input2.txt");
if (fin1 && fin2)
{ // if both files are in a good state, they're both open, write to output
std::cout << fin1.rdbuf()   // dump the contents of file 1 to output
<< ' '            // add a space
<< fin2.rdbuf();  // dump the contents of file 2 to output
return 0; // program successful
}
else
{ // at least one file failed to open
std::cerr << "File input failure"; // notify user of failure
return 1; // notify system of failure
}
}

最新更新