Input from Keyboard

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
#include <iostream>

using namespace std;
const int N = 3;

int main()
{
    int i, j;
	double matrix[N][N+1];
	int k = 1;
	for (i = 0; i < N; i++)
	{
		cout << "Enter value for equation " << k << ": " << endl;
		for (j = 0; j < N +1; j++)
		{
			cout << "[" << i << "]" << "[" << j << "] = ";
			cin >> matrix[i][j];
		}
		k++;
	}

	cout << "Your equation is: " << endl;
	for (i = 0; i < N; i++) {
		for (j = 0; j < N+1; j++) {
			cout << matrix[i][j] << "   ";
		}
		cout << endl;
	}
}


Can anyone help me how can I get any value of N from the keyboard but outside the main function? Because I still have some function outside of main using N
Last edited on
N is declared as const, so you won't be getting it from the keyboard unless you remove that qualifier.

If you want to dynamically size your matrix then you would be better using std::vector rather than these arrays.
Last edited on
I put const because the program didn't work without const. Does anyway that I can put the value of N from keyboard without using std::vector?
The size of an array has to be known to the compiler at compile time. Hence const int N = 3 is OK, but int N = 3 isn't as here N is a variable which can/could be changed at run-time so its value isn't known at compile time. If the size of an array is only obtained at run-time, then a variable sized container such as vector needs to be used.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
#include <iostream>
#include <vector>
using namespace std;

int main()
{
   int N;
   cout << "Enter the number of equations: ";   cin >> N;
   vector<vector<double>> matrix( N, vector<double>(N+1) );

   for ( int i = 0; i < N; i++ )
   {
      cout << "Enter values for equation " << i + 1 << ":\n";
      for ( int j = 0; j < N + 1; j++ )
      {
         cout << "[" << i << "]" << "[" << j << "] = ";
         cin >> matrix[i][j];
      }
   }

   cout << "Your augmented matrix is:\n";
   for ( int i = 0; i < N; i++ )
   {
      for ( int j = 0; j < N + 1; j++ )	cout << matrix[i][j] << "   ";
      cout << '\n';
   }
}


Enter the number of equations: 3
Enter values for equation 1:
[0][0] = 1
[0][1] = 2
[0][2] = 3
[0][3] = 10
Enter values for equation 2:
[1][0] = 4
[1][1] = 5
[1][2] = 6
[1][3] = 20
Enter values for equation 3:
[2][0] = 7
[2][1] = 8
[2][2] = 9
[2][3] = 30
Your augmented matrix is:
1   2   3   10   
4   5   6   20   
7   8   9   30   
Last edited on
Can anyone help me how can I get any value of N from the keyboard but outside the main function?
Why do you want to change N? You can use another variable. What do you want to do with the value from the keyboard?
Topic archived. No new replies allowed.