if statements and strings (c++)

Joined
Feb 15, 2005
Messages
651
I just started to try and teach myself c++ a couple of days ago and am currently working on a Tic Tac Toe program.

I'm wondering if there is a way to set up an if statement for a string. When I try something like :

if (loc == aa) {
aa = 1;
}
//Checks if string loc is equal to aa and sets aa = 1 if true

I get an error saying I'm trying to compare a pointer to an integer. I mostly understand why I'm getting this error but I'm wondering if there is a way to compare the text in the string is equal to other text. I hope this is clear, if it isn't respond telling me I'm an idiot and I need to rephrase it.
 
so loc is a string (i.e. did you #include <string> at the top, or is it a c-string char* ?) and aa is an int? if that's the case, you can't directly compare 2 different types. you have very little code to go on so i'm not going to say anything more without more code to see what you're doing exactly.
 
Ok, say I was comparing string "loc" with string "a1" in an if statement and if they are equal (contain the same text) then integer "aa" would be set to 1. Can you write this out for me. I'm a little confused by the link you gave me. That website looks to be a good resourse though.
 
This example is done with the C++ <string> class

Code:
#include <iostream>
#include <string>

int main(int argc, char **argv)
{
    std::string loc, aa1;
    int aa;

    // normally, we'd do stuff with loc and aa1, but this is just an example
    
    loc = "blah";
    aa1 = "blah";

    if(loc == aa1) aa = 1;
}

This following example is done with C-strings.

Code:
#include <cstring>

int main(int argc, char **argv)
{
    // once again, just an example, so we're just gonna declare a string when we initialize the variable
    char loc[] = "blah", a[] = "blah";
    int aa;

    if(strcmp(loc,a) == 0) 
        aa =  1;
}

Is 'aa' supposed to be true or false only? If so, it's better to use a bool data type.
 
Back
Top