Checking contents of char variable - C Programming
Solution 1
Daniel Haviv's answer told you what you should do. I wanted to explain why the things you tried didn't work:
if (decision == yes)
There is no identifier 'yes', so this isn't legal.
if (decision == "yes")
Here, "yes" is a string literal which evaluates to a pointer to its first character. This compares 'decision' to a pointer for equivalence. If it were legal, it would be true if they both pointed to the same place, which is not what you want. In fact, if you do this:
if ("yes" == "yes")
The behavior is undefined. They will both point to the same place if the implementation collapses identical string literals to the same memory location, which it may or may not do. So that's definitely not what you want.
if (sizeof (decision > 2))
I assume you meant:
if( sizeof(decision) > 2 )
The 'sizeof' operator evaluates at compile time, not run time. And it's independent of what's stored. The sizeof decision is 3 because you defined it to hold three characters. So this doesn't test anything useful.
As mentioned in the other answer, C has the 'strcmp' operator to compare two strings. You could also write your own code to compare them character by character if you wanted to. C++ has much better ways to do this, including string classes.
Here's an example of how you might do that:
int StringCompare(const char *s1, const char *s2)
{ // returns 0 if the strings are equivalent, 1 if they're not
while( (*s1!=0) && (*s2!=0) )
{ // loop until either string runs out
if(*s1!=*s2) return 1; // check if they match
s1++; // skip to next character
s2++;
}
if( (*s1==0) && (*s2==0) ) // did both strings run out at the same length?
return 0;
return 1; // one is longer than the other
}
Solution 2
You should use strcmp
:
if(strcmp(decision, "yes") == 0)
{
/* ... */
}
Solution 3
To compare you could use strcmp
like this:
if(strcmp(decision, "yes") == 0) {
// decision is equal to 'yes'
}
Also you should change char decision[3]
into char decision[4]
so that the buffer has
room for a terminating null character.
char decision[4] = {0}; // initialize to 0
Solution 4
Ok a few things:
decision
needs to be an array of 4char
s in order to fit the string "yes" in it. That's because in C, the end of a string is indicated by the NULchar
('\0'
). So yourchar
array will look like:{ 'y', 'e', 's', '\0' }
.- Strings are compared using functions such as
strcmp
, which compare the contents of the string (char
array), and not the location/pointer. A return value of 0 indicates that the two strings match. - With:
scanf("%s", &decision);
, you don't need to use the address-of operator, the label of an array is the address of the start of the array. - You use
strlen
to get the length of a string, which will just increment a counter until it reaches the NULchar
,'\0'
. You don't usesizeof
to check the length of strings, it's a compile-time operation which will return the value3 * sizeof(char)
for achar[3]
. scanf
is unsafe to use with strings, you should alternatively usefgets(stdin...)
, or include a width specifier in the format string (such as"3%s"
) in order to prevent overflowing your buffer. Note that if you usefgets
, take into account it'll store the newlinechar
'\n'
if it reads a whole line of text.
Solution 5
You should be especially careful with null-terminated string in C programming. It is not object. It is a pointer to a memory address. So you can't compare content of decision directly with a constant string "yes" which is at another address. Use strcmp() instead.
And be careful that "yes" is actually "yes\0" which will take 4 bytes and the "\0" is very important to strcmp() which will be recognized as the termination during the comparison loop.
Paul Morris
Updated on June 13, 2022Comments
-
Paul Morris almost 2 years
This might seem like a very simple question, but I am struggling with it. I have been writing iPhone apps with Objective C for a few months now, but decided to learn C Programming to give myself a better grounding.
In Objective-C if I had a UILabel called 'label1' which contained some text, and I wanted to run some instructions based on that text then it might be something like;
if (label1.text == @"Hello, World!") { NSLog(@"This statement is true"); } else { NSLog(@"Uh Oh, an error has occurred"); }
I have written a VERY simple C Program I have written which uses
printf()
to ask for some input then usesscanf()
to accept some input from the user, so something like this;int main() { char[3] decision; Printf("Hi, welcome to the introduction program. Are you ready to answer some questions? (Answer yes or no)"); scanf("%s", &decision); }
What I wanted to do is apply an
if
statement to say if the user entered yes then continue with more questions, else print out a line of text saying thanks.After using the scanf() function I am capturing the users input and assigning it to the variable 'decision' so that should now equal yes or no. So I assumed I could do something like this;
if (decision == yes) { printf("Ok, let's continue with the questions"); } else { printf("Ok, thank you for your time. Have a nice day."); }
That brings up an error of "use of undeclared identifier yes". I have also tried;
if (decision == "yes")
Which brings up "result of comparison against a string literal is unspecified"
I have tried seeing if it works by counting the number of characters so have put;
if (decision > 3)
But get "Ordered comparison between pointer and integer 'Char and int'"
And I have also tried this to check the size of the variable, if it is greater than 2 characters it must be a yes;
if (sizeof (decision > 2))
I appreciate this is probably something simple or trivial I am overlooking but any help would be great, thanks.
-
Daniel Haviv over 12 yearsAnd you char array should be 4 in size to fit in the null terminating value - forgive me for not explaining enough im writing through the iphone
-
Paul Morris over 12 yearsThat's ok Daniel, I literally just changed my code to if (strcmp(decision, "yes") == 0) and it worked, then I read your answer so thank you. So I assume by your answer that all C strings terminate in binary 0?
-
Paul Morris over 12 yearsThanks for the detailed explanation
-
AusCBloke over 12 yearsA note to the OP, you can initialize all elements in an array to 0 by just
char decision[4] = {0}
(even though you don't need to when using most C functions such asscanf
orfgets
. -
Paul Morris over 12 yearsHi, thanks for the answer. I ended up using if (strcmp("yes") == 0) which works fine.