I have two pointers to a string
user imputs the names. How do i use strcmp function to compare the first letters from two strings, so the function gives me TRUE if name1 and name2 begin with the same letter?Code:char *name1;
char *name2;
Printable View
I have two pointers to a string
user imputs the names. How do i use strcmp function to compare the first letters from two strings, so the function gives me TRUE if name1 and name2 begin with the same letter?Code:char *name1;
char *name2;
You don't. strcmp will compare the whole entire strings no matter what.
Bonus hint: the first letter of name1 is name1[0] and the first letter of name2 is name2[0].
it does now compile. It says "passins arg 2 of strcmp makes pointer from integer without a cast"
Im using pointers to a string (i have to).
If you ever need to compare a fixed-length of characters in a string, you can use strncmp(); Its the same as strcmp but it takes a third argument, which is the number of characters to compare.
Nothing wrong with using pointers to a string, but try and pay attention: you cannot solve this problem with strcmp. Strcmp operates on an entire string, not just the first character. To test characters for equality, you use ==.
Sigh. Why is it so difficult to understand these matters?
Read: http://cpwiki.sourceforge.net/A_pointer_on_pointers
Here's a hint. This is how you would compare the 3rd letter in two strings:
Now if you still can't figure out how to compare the 1st letters, well then I give up.Code:if ( str1[2] == str2[2] )
Surely, you can use strncmp to do that.
eg.
strncmp (name1, name2,1)
it returns 0 zero if they are equal to each other, or less than zero if first one less than second, or greater than zero if it is greater.