Topic: comparing two strings


Author: "Bradd W. Szonye" <bradds@concentric.net>
Date: 1998/03/30
Raw View
[Moderator's note: followups redirected to comp.lang.c++.moderated.
 -moderator of comp.std.c++ (fjh).]

agi wrote:
>
> Can somebody please tell me why the inner while loop doesn't
> recognise the null terminator or the space character . The index goes
> way outside the array bounds...

code snippet:
>       while (fp_string[i]!='\0' | fp_string!= " ") // problem here

Well, there are thre problems here; two are minor, the other is the root
of your problem. The minor "problem" is that you use '|' where you
probably mean '||'. The '|' operator is intended for bitwise OR; the
'||' operator is appropriate for Boolean OR.

Second problem is that you want to compare to character "space," not
string "space." Use the character ' ' in the second condition, not the
string " ". This might be just a typo, since it shouldn't even compile
(I think) with string " ".

Your main problem, however, is that you don't mean OR at all; you want
AND. Consider the logic:

    char    !='\0'  !=' '   OR     AND
    NUL     false   true    true   false
    space   true    false   true   false
    other   true    true    true   true

Notice that using OR means that your loop will never end. You definitely
want to use AND here. If you're still learning logic, some cases will be
troublesome for a while; this is one of them. Until you're confident
that you know what you're doing, you might want to build a truth table
like this. For more complicated cases, truth tables help even the
experts.

Three last remarks:

1. The code you actually want to use is:

    while (fp_string[i] != '\0' && fp_string != ' ') // ...

2. There may be other bugs in your code (I don't really have time to
examine it in depth), and you could probably use some help with coding
style and good practices as well. You seem like you're still learning
the language however, so you may pick these things up with time and
experience.

3. In the future, requests for help with code are more appropriate in
the newsgroup comp.lang.c++.moderated. This newsgroup is for discussing
the C++ standard; code help is really only appropriate when the
interpretation of new language features or the standard itself is
involved. Also be sure to look for the FAQ list for that newsgroup
before posting there. By the way, clc++.mod is a good place to pick up
style and practice tips as well.
--
Bradd W. Szonye
bradds@concentric.net
http://www.concentric.net/~Bradds

My reply address is correct as-is. The courtesy of providing a correct
reply address is more important to me than time spent deleting spam.
---
[ comp.std.c++ is moderated.  To submit articles, try just posting with ]
[ your news-reader.  If that fails, use mailto:std-c++@ncar.ucar.edu    ]
[              --- Please see the FAQ before posting. ---               ]
[ FAQ: http://reality.sgi.com/austern_mti/std-c++/faq.html              ]