0

I'm trying to compare user text input from an iphone app with the text in a static array I have declared. It is always returning "true", even when the text is different. After doing the strncmp, I display both text fields. To the human eye, they are what I expect the fields to be. The debugmsg I return to the screen shows what I expect the values to be, but the compare is always coming up true. Any suggestions would be appreciated. Thanks.

if (strncmp(SymbolEntered.text, 
[NSString stringWithCString:elements_table2[idx].element_symbol],2)==0)
{   
    DebugMsg.text = [NSString stringWithCString:"Correct answer"];
}
else 
{
    DebugMsg.text = [NSString stringWithCString:"Incorrect!"];
}

DebugMsg2.text = SymbolEntered.text;
DebugMsg3.text = [NSString stringWithCString:elements_table2[idx].element_symbol];
Mat
  • 202,337
  • 40
  • 393
  • 406
Rick
  • 49
  • 13

1 Answers1

7

You really should do this with NSString, which has tons of comparison methods implemented, instead of CString (why are you using CString?). strcmp doesn't work with NSString.

if([SymbolEntered.text isEqualToString:[NSString stringWithCString:elements_table2[idx].element_symbol]]) {
    DebugMsg.text = @"Correct answer";
} else {
    DebugMsg.text = @"Incorrect answer";
}

Also instead of:

DebugMsg.text = [NSString stringWithCString:"Correct answer"];

you can do this:

DebugMsg.text = @"Correct answer";
tamasgal
  • 24,826
  • 18
  • 96
  • 135
  • Just using CString out of ignorance. I had an earlier problem with a string and someone on this site suggested CString and it worked for what I was doing at the time (putting my static data in a text field) so I used it again in the strncmp. Thanks for the @ suggestion. I was trying just the quoted string and it wasn't working. I'm not used to that @ sign yet! – Rick Dec 28 '11 at 16:07
  • Your problem is, that you don't understand how to handle object oriented concepts. That's probably why you didn't got the other problem solved with NSString. NSString is much more powerful than a char*, so if you aren't that memory limited like on an IC, you should simply use NSString. I think strcmp is returning true just randomly, since it doesn't get the kind of data it expects. It should get a char* as input, but you're putting an NSString in it. So the whole bits and bytes are handled incorrectly. Just try it with other strings and I'm sure: sometimes you'll get true, sometimes false… – tamasgal Dec 28 '11 at 16:10
  • You're right about the object oriented concepts. I'm taking a c program I wrote and trying to get it to run on an iphone. Learning as I go about the object oriented concepts. Fortunately this is a pretty simple app. – Rick Dec 28 '11 at 16:27