C++ 输入多行以空格分隔的数将其变为数组,动态申请二维数组

#include 
#include 
#include 
using namespace std;


//输入两数表示数组的行和列
void input_n_m(int a[])
{
	char c;
	int i = 0;
	while ((c = getchar()) != '\n')
	{
		if (c != ' ')
		{
			ungetc(c, stdin);
			cin >> a[i++];
		}
	}
	//++++需要通过asscii码判断如果不是整数则.......
}

//多行数变为一行数
void input_num(vector circuit_column, vector& circuit_num)
{
	vector tem;
	tem = circuit_column;
	char c;
	int i = 0;
	while ((c = getchar()) != '\n')
	{
		if (c != ' ')//把这句判断条件改动
		{
			ungetc(c, stdin);
			cin >> tem[i++];
		}
	}
	//++++需要通过asscii码判断如果不是整数则.......
	//把新元素添加到后面
	circuit_num.insert(circuit_num.end(), tem.begin(), tem.end());
	tem.clear();
}


int main()
{
	int n = 0; //数组行
	int m = 0; //数组列
	int a[2] = { 0 };
	
	//1 输入数组行和列
	cout << "请输入两个整数要求大于0且小于1000" << endl;
	input_n_m(a);  

	n = a[0];
	m = a[1];

	//测试输入的两个整数正确与否?
	for (auto i : a)
	{
		cout << i << endl;
	}
	//2, 把输入的数变为容器或一维数组
	vector circuit_column(m);
	vector circuit_num;
	for (size_t i = 0; i < n; i++)
	{
		cout << "请输入" << m << " 个整数" << endl;
		input_num(circuit_column, circuit_num);
	}

	for (auto i : circuit_num)
	{
		cout << i << endl;
	}

	//3 把容器的数对应变为动态的二维数组
	int **B;
	B = new int*[n];
	for (int i = 0; i < n; i++)
		B[i] = new int[m];

	int k = 0;
	for (size_t i = 0; i < n; i++)
	{
		for (size_t j = 0; j < m; j++)
		{
			B[i][j] = circuit_num[k];
			k++;
		}
	}

	cout << "--------------------B-------------------" << endl;

	for (size_t i = 0; i < n; i++)
	{
		for (size_t j = 0; j < m; j++)
		{
			cout << B[i][j] << "  ";
		}
		cout << endl;
	}

	int **A;
	A = new int*[n];
	for (int i = 0; i < n; i++)
		A[i] = new int[m];

	for (size_t i = 0; i < n; i++)
	{
		for (size_t j = 0; j < m; j++)
		{
			if (B[i][j] == 1)
			{
				A[i][j] = 1;
			}
			else
				A[i][j] = 0;
		}
	}



	cout << "--------------------A-------------------" << endl;
	for (size_t i = 0; i < n; i++)
	{
		for (size_t j = 0; j < m; j++)
		{
			cout << A[i][j] << " ";
		}
		cout << endl;
	}


	//释放资源
	for (int i = 0; i < n; i++)
	{
		delete[] A[i];
		delete[] B[i];
	}
	delete[] A;
	delete[] B;

	system("pause");
	return 0;
}

你可能感兴趣的:(C/C++)