Friday, July 31, 2009

How to compare variables in c without using string compare (strcmp)?

i've assigned a certain value on a variable... and then i get input from the user, how will i compare the variable value to the input???

How to compare variables in c without using string compare (strcmp)?
If you mean to compare a number entered via the keyboard which is stored in a string to a value store in say an int then you need to convert the number in the string.





int userval, aval;





aval = 10;


sscanf(buf, "%d", %26amp;userval);


if (aval == userval) {


do something........


}


/* Where buf is the string entered */


Note this assumes the value is at the start of the buffer!





You can scan the input from the user directly into the var :-


scanf("%d", %26amp;userval);
Reply:A string in C is simply a pointer to characters, terminated by a null (zero) byte. All strcmp is doing is iterating over the strings comparing characters until it encounters the end of either string.





The following function is equivelent to the standard library function strlen, including the return value.





int compareStrings(const char* a, const char* b)


{


while (*a == *b++)


if (*a++ == 0)


return 0;


return (*(const unsigned char *) a - *(const unsigned char *) (b - 1));


}
Reply:You can use Array to Compaire.


No comments:

Post a Comment