is there a way to determine if 2D array have equal number of X and Y?

closed account (STR9GNh0)
as above

is there a way to determine if 2D array have equal number of X and Y?

like if my 2D array supposed to have 5 by 5

means 25 in total

and i deliberately enter 24 numbers to fill in the 5by5 leaving 1 out.

is there a way for me to detect that out and produce an error message?

thanks
Two ways to find the dimensions of the array are shown in this code:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
#include <iostream>

struct Size{ unsigned W, H; Size(int w, int h) : W(w), H(h) {} };

template< typename T, unsigned W, unsigned H >
Size GetSize( T (&t)[W][H] ){ return Size( W, H ); }

int main(){
   int arr[4][6];
   std::cout << sizeof(arr)/sizeof(arr[0][0]) << " = " << sizeof(arr)/sizeof(arr[0]) << " * " << sizeof(arr[0])/sizeof(arr[0][0]);
   Size sz = GetSize( arr );
   std::cout << " = " << sz.W << " * " << sz.H;
   std::cin.get();
   return 0;
}


I don't understand what you are asking though..
If you want to force the user to enter all 25 values, count how many have been entered and compare it to 25. If you only want to use the 24 values that have been entered, again, you only need to know many were entered..
closed account (STR9GNh0)
thanks..

imagine the user first entered the array size of 5.

5*5 gives you 25.

thus the number will have 25 numbers to entered in order to form a complete 5 by 5 2d array.

anything below that the program w exit out.

btw, is there a way to do it without the template?
Well, if the user has to enter a number of elements and you need to try to form an NxN matrix containing exactly that number of elements, then your criterion is met if the number entered is a perfect square.
closed account (STR9GNh0)
GONe
Last edited on
If you are concerned about the file containing not enough number or too many numbers, then you should do two things. First, check that line 14 succeeded (if( afile ) std::cout << "I succeeded";),
and second, after line 16 check that there a no more numbers in the file by attempting to read another and checking for failure (ie, not success).

That strategy assumes that the file format is irrelevant, and there can be any number of numbers on a line.

closed account (STR9GNh0)
.............
Last edited on
Topic archived. No new replies allowed.