How to compare char * to string literal in c ?

Home » Programming & Design » How to compare char * to string literal in c ?
Programming & Design No Comments

Hey guys, simple question that is stumping me. I need to compare a char * to a string literal. I know that it is coming through correctly, but how do I actually compare them. Here is an example segment (the actual program is huge, so I won't include it).

if(temp[0] != "1") //temp is type

Hey guys, simple question that is stumping me. I need to compare a char * to a string literal. I know that it is coming through correctly, but how do I actually compare them. Here is an example segment (the actual program is huge, so I won't include it).

if(temp[0] != "1") //temp is type char*
break;

it breaks every time, even when using debugger to be sure it does equal "1".

Best Answer:

michael: If you just need to compare the first character (or just one character) as in your example then you do it like this:

if (temp[0] != '1') <—– single quote, not double quote

if you need to compare the whole string then like this:

if (strcmp(temp, "mystring"))
//no match
else
//match

Other answer:

michael:
Your example is comparing a char to a string. You should use single quotes.

temp is a char* but temp[0] is a char.

Undisclosed:
temp[0] may have the value of "1", but that isn't enough to make it the same data type. temp[0] is an object on an array. You need to cast temp[0] to a string when making the comparison.
wg0z:
strcmp()

LEAVE A COMMENT