I have a Hexadecimal string hexa="ffffffff 0 0"; and an other string entered by the user from the console for example String="ffffffff 0 0";, i want to compare hexa to String in this case i want to have hexa equal String.
How can i do that,i'm working with C language i have searched around but i can't find an answer and i tried strcmp obviously did not work, I also tried sprintf(String2,"%s",hexa); then strcmp(String2,String) ;did not work either.
You most likely misinterpreted how strcmp works. It returns an integer which indicates the relationship between the strings. If you want to check whether they are equal, you should check if strcmp returned zero, like so:
if(strcmp(String,String2) == 0){
// Strings are equal
} else {
// Strings are not equal
}
Related
I have a struct here with something like:
char *sname;
........
players[i].sname
equalling "James".
I need to check for equality between values like so:
if (players[i].sname == 'Lee')
but am not having much luck. Is there a str* function I should be using or is there anyway to fix up my if statement?
The short answer: strcmp().
The long answer: So you've got this:
if(players[i].sname == 'Lee')
This is wrong in several respects. First, single-quotes mean "character literal" not "string literal" in C.
Secondly, and more importantly, "string1" == "string2" doesn't compare strings, it compares char *s, or pointers to characters. It will tell you if two strings are stored in the same memory location. That would mean they're equal, but a false result wouldn't mean they're inequal.
strcmp() will basically go through and compare each character in the strings, stopping at the first character that isn't equal, and returning the difference between the two characters (which is why you have to say strcmp() == 0 or !strcmp() for equality).
Note also the functions strncmp() and memcmp(), which are similar to strcmp() but are safer.
You should be using strcmp():
if (strcmp(players[i].sname, "Lee") == 0) { ...
Also note that strings in C are surrounded by double quotes: "". Single characters are surrounded by single quotes: ''. I'm not sure exactly what your compiler might be doing with 'Lee', but it's almost certainly not what you want.
You'd be looking for strcmp() from the header <string.h>.
Note that you need a string — 'Lee' is not a string but a multi-character constant, which is allowed but seldom useful, not least because the representation is defined by the compiler, not the C standard.
If you are looking to compare two strings — call the pointers to them first and second, then you write:
if (strcmp(first, second) == 0) // first equal to second
if (strcmp(first, second) <= 0) // first less than or equal to second
if (strcmp(first, second) < 0) // first less than second
if (strcmp(first, second) >= 0) // first greater than or equal to second
if (strcmp(first, second) > 0) // first greater than second
if (strcmp(first, second) != 0) // first unequal to second
This, in my view, makes it clear what the comparison is and so the notation should be used. Note that strcmp() may return any negative value to indicate 'less than' or any positive value to indicate 'greater than'.
You will find people who prefer:
if (strcmp(first, second)) // first unequal to second
if (!strcmp(first, second)) // first equal to second
IMO, they have the advantage of brevity but the disadvantage of being less clear than the explicit comparisons with zero. YMMV.
Be cautious about using strncmp() instead of strcmp(), which was suggested in one answer. If you have:
if (strncmp(first, "command", 7) == 0)
then if first contains "commander", the match will be valid. If that's not what you want but you want to use strncmp() anyway, you would write:
if (strncmp(first, "command", sizeof("command")) == 0)
This will correctly reject "commander".
strcmp works fine, provided one of the strings is null terminated. If both are max length and identical, the comparison will walk off the end, and most likely give a false negative result for the equality test. If one string is fixed inside of "" marks in the strcmp itself, that's not an issue, because we know it's null terminated.
If we are comparing two string variables, and we don't know if they are max length or not (maximum length ones are not null terminated), then we need to use strncmp, and use sizeof on one of them to get the third parameter. This solves the problem, because the sizeof is aware of the maximum length. Strcmp is 100% safe if one of the strings is a literal in double quotes.
I am new to C and I'm making my first "decent" program. I am facing trouble with my code.
char username[] = "root";
char usernametry[10];
scanf("%s",usernametry);
if (usernametry == username)
{
printf("Welcome ROOT user\n");
}
else
{
printf("Try again\n");
}
Whenever I execute my program, everything works; however, when I try to log in and type root as the username, it returns Try again. Can someone suggest why this is happening? I am very new to C so I apologize for my lack of C knowledge.
usernametry and username are arrays of type char. When you do usernametry == username, you are not comparing if two strings are equal, you are comparing the memory address of the first char in usernametry with the memory address of the first char in username. In order to compare if two strings are equal, you should use strcmp. Also, consider replacing %s in your scanf with %9s so that usernametry will never exceed 9 chars (which would have been a buffer overflow, as the 10th char needs to be '\0', the null character, which is used to terminate C-style strings).
You can't compare strings using ==, this is not a that-high-level-language. See strcmp() for comparing strings.
Incidentally, what if someone enters a name longer than 10 characters? You're drifting towards a buffer overflow bug in your code ;-)
use strcmp() functions to compare 2 strings instead of ==
use of == is wrong because in this case you compare address of usernametry and username and of course they are always differents.
if(strcmp(usernametry, username) == 0) // return 0 if equal !=0 if not equal
Use strcmp to compare two strings:
if(!strcmp(usernametry,username))
Your variables are not the same pointer.
Replace by:
if (!strcmp(usernametry, username))
In C, strcmp() function returns 0 if two strings are equal.
When I give a code like this,
char str[10] = "hello";
if(strcmp(str,strrev(str))==0)
{
printf("1");
}
else
printf("0");
This should print a 1 if its a palindromic string or it should print 0 if it is not a palindrome.
But it prints 1 even when the given string "hello" is not a palindrome. Where is the mistake?
What is strrev()? That's not a standard C function.
My assumption would be that it doesn't work like you think it does, i.e. it doesn't create and return a new heap copy of the string. Of course, if you expect that, then there's a bug that you don't retain the returned pointer so you can free() it when you're done.
Basically, you seem to expect C strings to behave like strings in a higher-level language, which they really don't.
strrev() is not a standatd C library function.
Your strrev() is reversing the actual string str first, then going for strcmp() with the changed string. So the results are always equal.
If you want to have the desired result:
make a copy of the original string
pass the original string to strrev()
compare with the earlier copy.
This question already has answers here:
Using the equality operator == to compare two strings for equality in C [duplicate]
(9 answers)
Closed 9 years ago.
Got a small problem with C. Restricting myself to simple C (i.e. OS instructions), and two strings seem to not be the same. Here is my code:
char inputData[256];
int rid;
rid = read(0,inputData,256);
// Strip input
char command[rid];
int i;
for (i = 0; i<=rid-2; i++) {
command[i] = inputData[i];
}
command[rid-1] = '\0';
if (command == "exit") {
write(1,"exit",sizeof("exit"));
}
Now, if a user enters "exit" into the terminal when queried and hits enter, the if for detecting "exit" never gets run. Any ideas?
Thanks,
EDIT: I am commiting to git as I go, so the current version can be found at github.com/samheather/octo-os. It's very obviously not complete code, but it demonstrates the problem.
You can't compare strings with ==. You need to use strcmp.
if (strcmp(command, "exit") == 0) {
C strings are actually character arrays. You can think of "command" as a pointer to the first character. You want to compare every character in the string, not just the location of the first characters.
You should use strcmp to compare strings in C.
if(strcmp(command, "exit") == 0) //strcmp returns 0 if strings are equal
To quote:
A zero value indicates that both strings are equal. A value greater than zero indicates
that the first character that does not match has a greater value in str1 than in str2.
a value less than zero indicates the opposite.
As it stands right now, you're comparing the address of command with the address of the string literal "exit", which pretty much can't be the same.
You want to compare the contents, with either strcmp, or (if "only OS instructions" means no standard library functions) an equivalent you write yourself that walks through the strings and compares characters they contain.
As others said, == doesn't work with strings. The reason is that it would compare the pointers given.
In the expression
command == "exit"
command is a pointer to your array variable, while "exit" is a pointer to that string which resides in read-only data space. They can never be identical, so the comparison always is false.
That's why strcmp() is the way to go.
Use strcmp from the standard library.
This question already has answers here:
strcmp behaviour in 32-bit and 64-bit systems
(3 answers)
Closed 9 years ago.
So I have this (not the full code)
char list[1000][10];
strcpy(list[0],"ab");
printf("%d\n",strcmp(list[0],"ab"));
and the strcmp is returning 0. Can somebody explain why it's doing so?
Thanks in advance.
The strcmp method will return 0 if list[0] contains "ab" in this case.
It returns:
Returns an integral value indicating the relationship between the strings:
A zero value indicates that both strings are equal.
A value greater than zero indicates that the first character that does not match has a greater value in str1 than in str2; And a value less than zero indicates the opposite.
strmp returns 0 when the strings match. Unless I am missing something, it's behaving as expected.
see: http://www.tutorialspoint.com/ansi_c/c_strcmp.htm
strcmp() does an ordinal comparison of the strings, not an equality test. The return value of 0 means the strings are equal!
If you want to test for equality use this pattern:
if (strcmp(s, "ab") == 0) {
// strings are equal
}
Because strcpy() is a function that copies the "right" string to the "left" string.
So, after strcpy(list[0],"ab");, the content of list[0] is "ab".
Then, they are equal strings, and strcmp returns 0, which means "equal".
Your String is matched that is why it is returning 0
do like this...
char list[1000][10];
strcpy(list[0],"ab");
if(strcmp(list[0],"ab")==0)
printf("Matched\n",);
As mentioned by Daniel, the returnd value is 0.
Taken from cplusplus.com
Returns an integral value indicating the relationship between the
strings: A zero value indicates that the characters compared in both
strings form the same string. A value greater than zero indicates
that the first character that does not match has a greater value in
str1 than in str2; And a value less than zero indicates the opposite.
You should also work with strncmp rather than with strcmp.