converting strings
bnikkel
Posts: 104
in Propeller 1
I was on a roll this morning and now I'm stumped. I have several "if" statements that I need to compare a known variable to an incoming string. I believe my problem is that I need to convert the string to an array before the if statement? any thoughts? the first print command works perfect I get MAIN or VIC1 but everything I have tried never gets to the second print command.
char rxchar = 0; // int i = 0; char string[4]; fdserial_rxFlush(lcd); // flush rx buffer while(rxchar != '\r' && rxchar != '\n') { // no CR or LF rxchar = fdserial_rxChar(lcd); // get char string[i] = rxchar; // append char i++; } string[i] = '\0'; // append NULL pause(100); print("name= %s\n",string); if (string == "MAIN") { // 33333 MAIN print("inside\n"); }
Comments
if (strcmp(string,"MAIN") == 0) { print("got MAIN\n"); }
I think you have to include the declarations from <string.h>
If you use a better checksum (like a CRC) than just a simple sum, you decrease the chances of other strings having the same value. But you should really just compare the original strings using strcmp() or something equivalent.
The only case I can think of where relying on a checksum actually makes sense is if you need to test pairs of vast quantities of long strings for equality (in which case you'd use a real cryptographic checksum like SHA-1 or SHA-256).
This was only an example and offered as an alternative not a must do. If it does not fit for the particular scenario then one should do something else.
However, in other embedded situations I've been involved with libs such as 'string.h' were not available so a manual workaround had to be used.
Again, it was offered as an alternative and example.
It's a bit off topic of the post, however with regards to whether a compiler would add non used parts of string.h in the compiled code depends on the linker that is used. If the compiler has a lazy linker, then it is possible that all of what is in something such as 'string.h' could be added to the code. Also, if the included code contains static or inline defines it is possible that these could be added to the code even if they are not used.
It would be nice if in 'C' there was the option to include portions of the include like with Python.
Something like:
from string.h include strcmp
This way there would be no question as to what is added to the compiled code. Well, outside any baggage strcmp may carry with it.