there has been a lot of changes in my program, recently. i'm now working on a program which lets the user make and display a matrix.
Code:
#include <stdio.h>
#include <string.h>
void make_mat();
char cmd_str[50]="\0";
char *array[50];
char get_cmd();
int mat_A[50][50], mat_B[50][50], mat_C[50][50];
int r1, c1, r2, c2, r3, c3, i, j;
int loop;
int main()
{
while(1)
{
get_cmd();
if (strcmp(array[0], "MAKE")==0)
make_mat();
else if (strcmp(array[0], "DISP")==0)
printf("DISP");
else
printf("Invalid Command!");
}
}
/*Get Command Function*/
char get_cmd()
{
printf("\n>>");
gets(cmd_str);
array[0]=strtok(cmd_str," ");
if(array[0]==NULL)
{
printf("Error.\n");
}
for(loop=1;loop<50;loop++)
array[loop]=strtok(NULL," ");
return (*array[0]);
}
/*Make Function*/
void make_mat()
{
if (strcmp(array[1], "A")==0)
{
printf("Enter rows: ");
scanf("%d", &r1);
printf("Enter columns: ");
scanf("%d", &c1);
for(i=0;i<r1;i++)
for(j=0;j<c1;j++)
{
printf("A[%d][%d] = ", i, j);
scanf("%d",&mat_A[i][j]);
}
}
else if (strcmp(array[1], "B")==0)
{
printf("Enter rows: ");
scanf("%d", &r2);
printf("Enter columns: ");
scanf("%d", &c2);
for(i=0;i<r2;i++)
for(j=0;j<c2;j++)
{
printf("A[%d][%d] = ", i, j);
scanf("%d",&mat_B[i][j]);
}
}
else if (strcmp(array[1], "C")==0)
{
printf("Enter rows: ");
scanf("%d", &r3);
printf("Enter columns: ");
scanf("%d", &c3);
for(i=0;i<r3;i++)
for(j=0;j<c3;j++)
{
printf("A[%d][%d] = ", i, j);
scanf("%d",&mat_C[i][j]);
}
}
}
there, but now, it has 2 problems:
a. if the user only typed MAKE, the program will immediately crash.
-will crash
b. if the user typed MAKE A, it is fine. but, after completing the matrix(filling the rows), the program will print >>Error then, immediately crash.
Code:
>>MAKE A
Enter row: 2
Enter column: 2
A[0][0] = 1
A[0][1] = 2
A[1][0] = 3
A[1][1] = 4
>>Error.
-also crashes
New_Ink2001 told me that i should try moving the loop for tokenizing so that it is not run when get_cmd decides it's got an error or perhaps avoid tokenizing the string entirely if it is empty because strtok and gets are both somewhat misfits.
how should i do that?