comparing strings
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;
}
evilsilver
Junior Poster in Training
84 posts since Feb 2005
Reputation Points: 10
Solved Threads: 1
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.
evilsilver
Junior Poster in Training
84 posts since Feb 2005
Reputation Points: 10
Solved Threads: 1
>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.
Narue
Bad Cop
15,460 posts since Sep 2004
Reputation Points: 6,464
Solved Threads: 1,401
yes you can asign them with =, try this
char *test = new char [100];
test = "this works";
That's not assigning astring. That's assigning a pointer (and a memory leak).
Dave Sinkula
long time no c
5,058 posts since Apr 2004
Reputation Points: 2,780
Solved Threads: 314
evilsilver
Junior Poster in Training
84 posts since Feb 2005
Reputation Points: 10
Solved Threads: 1