Matrix of chars

I have a problem who reads a matrix with nxm elements of strings and have to display the string which has the biggest length from each line.

Here's my code:

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
#include <iostream>
using namespace std;
int main ()
{
	char mat[100][100][100], t[100];
	int n, m, i, j, max=0;
	cout << "n= "; cin >> n;
	cout << "m= "; cin >> m;
	for (i=0; i<n; i++)
	{
		for (j=0; j<m; j++)
		{
			cout << "mat[" << i << "][" << j << "]= "; cin >> mat[i][j]; 
		}
	}
	for (i=0; i<n; i++)
	{
		for (j=0; j<m; j++)
		{
			if (max>strlen (mat[i][j]))
			{
				strcpy (max, strlen(mat[i][j]));
				strcpy (t, mat[i][j]);
			}
		cout << t << endl;
	}
	
}


The problem is that the compiler cannot compare two different types as you know (max>strlen (mat[i][j])) and i don't know how to change it. Any tip would be appriciated! Thank you!
By the way, i work in mingw.
Hey buddy,

just cast it!

1
2
if(max > static_cast<int>(strlen(mat[i][j]))
...


But I think this is not the problem. strlen works for NULL terminated characters, which means, your string has to end with NULL for strlen to work, here's an example:

1
2
3
4
5
6
char[100] mystr;
mystr[0] = 'g'
mystr[1] = 'j'
mystr[2] = 'e'
mystr[3] = 'a'
mystr[4] = 'y'



Now if you use strlen with this, you'll get a wrong answer. To get the right answer, you have to add this line too:

 
mystr[5] = NULL;


Your array doesn't differ conceptually whatsoever from an int array except that char's size is 1 byte. Can you ever measure the length of an array of ints? not really! So to do it, you have to terminate your string with a NULL like I mentioned. It's some kind of a special hack to make strings defined in size.

http://www.cplusplus.com/reference/clibrary/cstring/strlen/

Cheers :)
Last edited on
I think that you need not three dimensional matrix.

char mat[100][100][100], t[100];
Since you're using c++, why don't you use std::string?

1
2
3
4
string mat[200][200];
// ...
if(mat[i][j].length() > max)
    max = mat[i]j[].length();
Last edited on
Thank you guys! I found the mistake now!
Topic archived. No new replies allowed.