the kind of question ya feel embarassed to ask... (if char == "bla")

Started by
6 comments, last by Nibbles 21 years, 3 months ago
hi, I was wondering how to properly do the following:
  
char caption[80];

strcpy(caption, "Hello");

if (caption == "Hello")
   printf("yo");
else
   printf("bye");
  
This doesn''t work for me, and i''m sure i''ve done this before, but for the life of me, i can''t remember how. Thanks, Soott
------------------------------------------------------------
Email
Website

"If you try and don''t succeed, destroy all evidence that you tried."
------------------------------------------------------------
Advertisement
Use strcmp(str1, str2) or stricmp(str1, str2) stricmp is a case-insensitive comparision whereas the other is case sensitive.
you are comparing pointers (the address of the first byte of caption and the address of the first byte in the const string "Hello" ), which won't be the same.
you want to strcmp() them...

EDIT: i almost answered first...

[edited by - krez on December 23, 2002 10:52:51 PM]
--- krez ([email="krez_AT_optonline_DOT_net"]krez_AT_optonline_DOT_net[/email])
Or use std::string which defines an overloaded == operator. What is it with clinging to C today anyway?
--God has paid us the intolerable compliment of loving us, in the deepest, most tragic, most inexorable sense.- C.S. Lewis
It''s a little easier with c++-style strings:
  string caption;caption = "Hello";if (caption == "Hello")  // equalelse  // not equal  
groovy,

thank you!
Scott


------------------------------------------------------------
Email
Website

"If you try and don''t succeed, destroy all evidence that you tried."
------------------------------------------------------------
quote:Original post by antareus
... What is it with clinging to C today anyway?

Just learning the concept of the so-called null-terminated string .

500x2

[EDIT] btw, here's the C version:

  char caption[80];strcpy(caption, "Hello");if ( strcmp(caption, "Hello") == 0 )     printf("yo");else     printf("bye");  


[edited by - DerekSaw on December 23, 2002 11:00:49 PM]
"after many years of singularity, i'm still searching on the event horizon"
Don''t know why but I don''t like C++ strings. I prefer C style strings. I think the C++ way is misleading. I think the C way makes more sense. Guess I''m just old-school.

This topic is closed to new replies.

Advertisement