I am trying to make a program that needs to compare a string. here is a basic program of what i mean, i want it to say "it worked" but it seems to only read as not true. anyone know how to do this? thanx for any help.

#include <iostream>
#include <conio>
#pragma hdrstop
#include <condefs.h>


//---------------------------------------------------------------------------
#pragma argsused
int main(int argc, char **argv)
{
char *name = new char [100];
cout << "the word is silver (all lower case)." << endl;
cout << "enter name:";
cin >> name;
    if (name == "silver") {
        cout << "it worked." << endl;
    }
    else if (name != "silver"){
        cout << "it didn't work." << endl;
    }
cout << name;
getch();
return 0;
}

You can't compare strings with == (just like you can't assign strings with = ), use:

if ( strcmp( first_string, second_string) == 0 )

You can't compare strings with == (just like you can't assign strings with = ), use:

if ( strcmp( first_string, second_string) == 0 )

yes you can asign them with =, try this

char *test = new char [100];
test = "this works";

p.s. i tried what you said and it work.

(Ah, my bad, forgot that you could with char * = rather than with char [] which requires strcpy.)

>yes you can asign them with =, try this
Brilliant Holmes, nice memory leak you've got there. First you assign memory to a pointer, then you reseat the pointer to a string literal, thus losing a reference to the memory you just allocated.

You need to figure out the difference between an array, a pointer, and a string before trying stuff like that.

yes you can asign them with =, try this

char *test = new char [100];
test = "this works";

That's not assigning a string. That's assigning a pointer (and a memory leak).

lol good point sorry.

When I run your programme using Dev C++ at the line

if (name == "silver") {

I add-watch to the comparison

name == "silver"

I get

name == {115's', 105'i', 108'l', 118'v', 101'e', 114'r', 0'\0'}

name occurs like C string and is delimited by '\0'. So name is "silver\0" but not "silver".

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.