I'm trying to do a simple compare and it's not working. Const char *

Hi

Here is part of a simple function. The simple testing of equality doesn't work

Even if the const char * inputfile is "generate". It stills fails.

Vivienne

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// code to handle actual commans
void ExistenceClient::loadScene(const int mode, const char * inputfile)
{
    // get resources
    ResourceCache* cache = GetSubsystem<ResourceCache>();
    Renderer* renderer = GetSubsystem<Renderer>();
    Graphics* graphics = GetSubsystem<Graphics>();
    UI* ui = GetSubsystem<UI>();
    FileSystem * filesystem = GetSubsystem<FileSystem>();
    int testgenerate=1;

        // create variables (urho3d)
    String InputDataFile;

    InputDataFile.Append(filesystem->GetProgramDir().CString());
    InputDataFile.Append("Resources/Scenes/");
    InputDataFile.Append(inputfile);

    cout << &inputfile[0];

    if(&(*inputfile)=="generate")
    {
        GenerateScene();

        return;
    }
Last edited on
To compare an array of characters (c-string) to a string (std::string) you would you have to use a for loop or strcmp not ==. You could however change it from a c-string to a c++ string (std::string)
c-strings, i.e. char*, are just pointers to memory. For your char *inpufile, inputfile will point to the first character of your c-string. When you de-references it (line 21) using *inputfile, you get the first character only. Taking the address, i.e. &, brings you back to the pointer.

If you want to (or are required to) use c-strings you should use strcmp as suggested by gitblit. Line 21 turns into:
if ( strcmp( inputfile, "generate" ) == 0 )

Using std::string it morphs into:

1
2
3
std::string mystring( inputfile ); // in order to make the std::string from inputfile. 

if ( mystring == string( "generate" ) )


... or:

if ( mystring.compare( "generate" ) == 0 )

I recommend using std::string. It is portable, has a lot of functionality build in - and cleans up after itself.
Last edited on
Thank you. It's resolved.
Topic archived. No new replies allowed.