我的愚蠢问题可能有一个简单的答案,但我现在似乎无法在逻辑上思考。
到目前为止我所拥有的是创建2D数组(基于用户输入的维度)并为数组的每个元素生成随机数的功能。
下一部分是我被困的地方......
如何将此2D数组移动到另一个将其导出到文本文件中的函数?
如果我是对的并且有一个简单的解决方案,你还能告诉我该怎么做。我更像是一个视觉学习者。
-Thanks
# 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);
}
答案 0 :(得分:1)
例如:
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而你不能在构造函数ofstream中传递字符串,你需要使用字符串的c_str()方法。在视觉工作室中,如果没有这些更正,它将会工作,但这可能会有所帮助。 如果我们使用new,我们需要使用delete来防止内存泄漏。
答案 1 :(得分:0)
您可以使用相同的嵌套for循环将数组插入到用于将值插入数组的文件中
答案 2 :(得分:0)
for (int y = 0; y < rows; y++) {
for (int x = 0; x < columns; x++) {
// write Array[y][x] to file here
}
}