Thread: problem comparing strings with strcmp

  1. #1
    Registered User
    Join Date
    Dec 2001
    Posts
    3

    Question problem comparing strings with strcmp

    given two strings:

    r_words[i].word = "auto"; // from a struct
    s[] = "auto";

    then compared with this code:

    int f;
    f = strcmp(r_words[i].word, s);
    if(!f)
    cout << ........

    I can't understand why strcmp doesn't seem to recognize that both strings are identical. Thanks for any suggestions. Mike

  2. #2
    Registered User mlupo's Avatar
    Join Date
    Oct 2001
    Posts
    72
    Try printing out each value to stdout just before you compare them.

    I think that the struct r_words[i].word might be referencing the wrong string in the array of structures. make sure that i is referencing the string you really think it is referencing.
    again, by printing them out just before you compare them will give you some visibility into your problem.


    Mike
    NEVER PET YOUR DOG WHILE IT'S ON FIRE!

  3. #3
    Registered User mlupo's Avatar
    Join Date
    Oct 2001
    Posts
    72
    here's a little clever way to test this without initializing a variable.
    you had
    Code:
    int f; 
    f = strcmp(r_words[i].word, s); 
    if(!f)
    try this....
    Code:
    if(!strcmp(r_words[i].word, s) )
    it's fewer lines of code, thus it's easier to read.
    try to get in that habit now.
    NEVER PET YOUR DOG WHILE IT'S ON FIRE!

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Problem with Strings, Please help!
    By varus in forum C++ Programming
    Replies: 8
    Last Post: 11-27-2006, 11:47 PM
  2. Problem with strings
    By PPhilly in forum C++ Programming
    Replies: 2
    Last Post: 04-09-2006, 06:56 PM
  3. Problem with seperating strings with delimiters..
    By hykyit in forum C Programming
    Replies: 2
    Last Post: 03-29-2006, 06:51 PM
  4. problem with an array of strings in C
    By ornamatica in forum C Programming
    Replies: 14
    Last Post: 05-01-2002, 06:08 PM
  5. problem with strings (explained)
    By dune911 in forum C Programming
    Replies: 9
    Last Post: 02-11-2002, 06:02 PM