Reputation: 201
So we were asked to create a program that enables the users to choose an option from 1-6 about matrix operations. In each user's input, we need to check if this input is eligible for the operation to be done(the program should accept INTEGERS or FLOATING POINT, positive or negative). If the criteria above is not met, we will ask the user again to enter another value until the user correctly inputs a right input.
This is a snippet of my program:
printf("[A] You chose Matrix Addition\n");
printf("How many columns would you like?\n");
fgets(rows,sizeof(rows),stdin);
r=atoi(rows);
printf("How many rows would you like?\n");
fgets(columns,sizeof(columns),stdin);
c=atoi(columns);
printf("Enter the elements of first matrix\n");
for (e = 0; e < c; e++) {
for (f = 0; f < r; f++) {
printf("Element [%d][%d]:\n",e,f);
fgets(elem1,sizeof(elem1),stdin);
a=atof(elem1);
first[e][f]=a;
}
}
printf("Enter the elements of second matrix\n");
for (e = 0; e < c; e++) {
for (f = 0; f < r; f++) {
printf("Element [%d][%d]:\n",e,f);
fgets(elem2,sizeof(elem2),stdin);
b=atof(elem2);
second[e][f]=b;
}
}
printf("Sum of entered matrices:-\n");
for (e = 0; e < c; e++) {
for (f = 0 ; f < r; f++) {
sum[e][f] = first[e][f] + second[e][f];
printf("%.3f\t", sum[e][f]);
}
printf("\n");
}
my problem is, what should I do to be able to (1) check if the input is eligible and (2) how do I ask the user to enter another again.
*We were not allowed to use scanf and other "unsafe" string functions such as puts, gets, strlen, etc. *The program above works already FOR integers only and it does not tell if the user's input is invalid. How do I do that? Thanks.
Upvotes: 0
Views: 72
Reputation: 122
You can do that as:
// I am providing just hint..
do {
printf("Enter Element [%d][%d]:\n",e,f);
fgets(elem1,sizeof(elem1),stdin);
a=atof(elem1);
}while(!notDesiredValue(a));
Now implement notDesiredValue(flaot number)
yourself to match your desired condition....Is it helpful...
Upvotes: 0