We'll use a loop, also. This is a loop called a "binary search". I just woke up (5:19 on the Wet Coast), so let me turn on the coffee maker and I'll post it up with an edit to this post.
Just to be clear on something. Only the receive messages are sorted, right? The tx messages should NOT be sorted, but be in the same index number as the received message that they are correct for.
We don't need an index number put into the string, unless each receive message can have more than one tx message that needs to go out.
The index number we need will be FOUND implicitly, NOT explicitly. We have no need to list that correct index number, anywhere in the code.
Back in a bit.
Code:
/* Using parallel arrays for one to one implicit indexing by Adak
status: ok
*/
#include <stdio.h>
#define ROW 10
#define COL 20
int binarySearch(char rx[ROW][COL], char *msg);
int binarySearch(char rx[ROW][COL], char *msg) {
int lo, mid, hi, num;
lo = 0;
hi = ROW -1;
while(lo <= hi) {
mid = (lo + hi) / 2;
num = strcmp(rx[mid], msg);
if(num > 0)
hi = mid - 1;
else if(num < 0)
lo = mid + 1;
else
return mid; //msg was found, return the index to it
}
return 0; //msg was not found
}
int main() {
int i, r, c, found;
char msg[COL + 1];
char rx[ROW][COL] = { //this is the array that is sorted
{"00 00"},
{"11 11"},
{"22 22"},
{"33 33"},
{"44 44"},
{"55 55"},
{"66 66"},
{"77 77"},
{"88 88"},
{"99 99"}
};
char tx[ROW][COL] = { //this is implicitly linked to the rx array
{"answer for zero"},
{"answer for one"},
{"answer for two"},
{"answer for three"},
{"answer for four"},
{"answer for five"},
{"answer for six"},
{"answer for seven"},
{"answer for eight"},
{"answer for nine"}
};
do {
printf("\n\n\n Enter your message [nn nn format, or q to quit]: ");
for(i = 0; i <= COL; i++)
msg[i] = '\0';
fgets(msg, sizeof(msg), stdin);
i = strlen(msg);
while(i > -1) {
if(msg[i] == '\n')
msg[i] = '\0';
--i;
}
found = binarySearch(rx, msg);
if (found)
printf("\nMessage was located: %s Reply is: %s \n", rx[found], tx[found]);
else if(msg[0] != 'q')
printf("\nMessage %s was not found\n", msg);
}while(msg[0] != 'q');
printf("\n\n\t\t\t press enter when ready");
i = getchar();
return 0;
}
With just a few dozen messages, a binary search is a bit of overkill, but it's a great tool to know. When the data gets thick as thieves, binary search really comes into it's own.