我的愚蠢问题可能有一个简单的答案,但我现在似乎无法进行逻辑思考。
到目前为止,我拥有的是创建二维数组(基于用户输入的维度)并为数组的每个元素生成随机数的函数。
下一部分是我卡住的地方......
如何将这个二维数组移动到另一个将其导出到文本文件的函数中?
如果我是对的并且有一个简单的解决方案,您能否仍然告诉我如何去做。我更像是一个视觉学习者。
-谢谢
# include <iostream>
# include <fstream>
# include <string>
# include <ctime>
using namespace std;
void Array(int rows, int columns)
{
int **Array = new int*[rows];
for (int i = 0; i < rows; ++i)
Array[i] = new int[columns];
for (int y = 0; y < rows; y++)
{
for (int x = 0; x < columns; x++)
{
Array[y][x] = rand();
}
}
}
void File()
{
string Name;
cout << "Enter a file name you would like the array to be located under.\n";
cin >> Name;
Name = Name + ".txt";
ofstream fout(Name);
// This is where i would have the array inserted into the text file...
fout.close();
}
int main()
{
int rows, columns;
cout << "Input the number of columns you would like to have in the array. \n";
cin >> columns;
cout << "Input the number of rows you would like to have in the array. \n";
cin >> rows;
srand(time(NULL));
Array(rows, columns);
File();
system("pause");
return (0);
}
最佳答案
例如:
using namespace std;
int** Array(int rows, int columns)
{
int **Array = new int*[rows];
for (int i = 0; i < rows; ++i)
Array[i] = new int[columns];
for (int y = 0; y < rows; y++)
{
for (int x = 0; x < columns; x++)
{
Array[y][x] = rand();
}
}
return Array;
}
void File(int **arr, int rows, int columns)
{
string Name;
cout << "Enter a file name you would like the array to be located under.\n";
cin >> Name;
Name = Name + ".txt";
ofstream fout(Name.c_str());
for (int y = 0; y < rows; y++)
{
for (int x = 0; x < columns; x++)
{
fout<<arr[y][x]<<" ";
}
fout<<endl;
}
fout.close();
}
int main()
{
int rows, columns;
cout << "Input the number of columns you would like to have in the array. \n";
cin >> columns;
cout << "Input the number of rows you would like to have in the array. \n";
cin >> rows;
srand(time(NULL));
int **array = Array(rows, columns);
Array(rows, columns);
File(array, rows, columns);
system("pause");
for (int y = 0; y < rows; y++)
{
delete []array[y];
}
delete []array;
return (0);
}
请注意,您忘记为系统包含 cstdlib,并且您不能在流的构造函数中传递字符串,您需要使用字符串的 c_str() 方法。在 visual studio 中,它可以在没有这种修正的情况下工作,但也许这会有所帮助。 如果我们使用 new,我们需要使用 delete 来防止内存泄漏。
关于c++ - 使用 C++ 函数将二维数组转换为文本,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34102391/