|
-
October 5th, 2009, 10:48 AM
#1
Problems with strcmp
Hey,
basically I'm starting with C++, I've already learned quite a lot and I now wanted to start with a simple game of Tic Tac Toe.
So now that's the problem:
I'm basically trying to check if there's an "X" or a number saved in a char of an array. But that doesn't seem to work:
Code:
if (!strcmp(field[1],"X") == 0)
So I'm just wondering what I'm doing wrong, I guess I just need a different function, but I simply can't find something that would work.
Thanks in advance.
-
October 5th, 2009, 11:22 AM
#2
Re: Problems with strcmp
What is the type of "field"?
Since char is a primitive type, you can compare individual characters just using ==. You need to use a character literal rather than a string literal though.
-
October 5th, 2009, 11:59 AM
#3
Re: Problems with strcmp
Well, the declaration of the variable looks like that:
Code:
char field[11] ={'0','1','2','3','4','5','6','7','8','9'};
But throughout the process of the game and code the numbers may change to 'X' or 'O'. That's why I think I need strcmp, because you can't compare letters with a simple == operator, can you?!
-
October 5th, 2009, 12:26 PM
#4
Re: Problems with strcmp
Code:
if (!strcmp(field[1],"X") == 0)
Using '!' as well as '==0' check?
Weird!
-
October 5th, 2009, 12:50 PM
#5
Re: Problems with strcmp
You can:
Code:
if ( field[some_position] == 'X' ) ...
But why you created array of 11 elements and assigned 10 elements, Tic Tac Toe only has 9.
When you exactly know how many elements are there, and there is actually none of string operations involved, you need not to worry about null character!
-
October 5th, 2009, 02:40 PM
#6
Re: Problems with strcmp
strcmp checks null terminated strings for equality. field[1] is not a null terminated string. Use strstr or just iterate each char in the array looking for it.
-
October 5th, 2009, 02:44 PM
#7
Re: Problems with strcmp
 Originally Posted by GCDEF
Use strstr or just iterate each char in the array looking for it.
I would recommend strchr for single character search.
-
October 7th, 2009, 01:34 AM
#8
Re: Problems with strcmp
if ( field[some_position] == 'X' ) should solve your problem.
no need of strcmp as u field is char.
Tags for this Thread
Posting Permissions
- You may not post new threads
- You may not post replies
- You may not post attachments
- You may not edit your posts
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|