![]() |
Howto compare two strings in C
Hi,
I want to compare two strings in C, where one string is recieved from a program's argument, and the other comes from a variable. I want to execute a command when the strings are equal. Can someone show me how that can be done please? I have tried several things but I can't get it to work. Thanks a lot. Ben |
man strcmp
example: Code:
#include <string.h> |
Thanks for the quick response Dark_Helmet. I am going to try this out.
Regards, Ben |
I have got it working. Thanks for the help Dark_Helmet.
Ben |
|
Quote:
Ben |
I would like to assign the programs argument to a variable and then use that variable with the strcmp command, instead of using argv[1] directly, but I am unable to achieve that.
What is the proper way of doing this? I can't figure it out. Thanks Ben :jawa: |
use strcpy, as argv[1] is a string
Code:
char var[10]; |
should it not be ?
char var[10]; strcpy(var,*(argv+1)); by the way would would ideally want to make sure that argv[1] will fit inside var b4 copying as strcpy will not check to see if there is space. Try it and see. :0) make your program arguement longer than 10 characters and the program will more than likely seg fault. |
Thanks a lot for the help guys. I will try this out this afternoon.
Ben http://www.artis.nl/paginas/t/dieren...img/keizer.jpg |
Space does need to be allocated for the local variable receiving the copy. This is code I typically use:
Code:
arg_length = strlen( argv[i] );Of course, the above code assumes a number of things: 1. arg_copy is defined as a char * 2. arg_length is some sort of integer values (I always use "unsigned" ) 3. the variable 'i' has been properly declared and initialized 4. there is a command-line argument corresponding to i's value 5. the malloc() call succeeds 6. the memset() call succeeds 7. the strncpy() call executes without error (i.e. all chars copied) Each step can be verified, but I'm too lazy to add it in and it would obfuscate the whole point of the code anyway. |
strcpy will take 2nd argument as *(argv+1) as strcpy takes a pointer as 2nd arg.
for variable var the size should be = to strlen(*(argv+1)) |
Quote:
Code:
STRLEN(3) Linux Programmer's Manual STRLEN(3) |
I did not have the oppurtunity to try out your suggestions, but you have been really helpfull.
I'll try to post about the result tommorow. Thanks again, Ben |
Quote:
Code:
char out[256]; |
| All times are GMT -5. The time now is 06:46 PM. |