Thread: Evaulating a char string?

  1. #1
    Registered User
    Join Date
    Mar 2009
    Posts
    28

    Evaulating a char string?

    Is is done like this? I can't get it to work.

    Code:
    if(char[] == "I love cheese."){
    }

  2. #2
    Registered User
    Join Date
    Sep 2006
    Posts
    8,868
    Quote Originally Posted by motionman95 View Post
    Is is done like this? I can't get it to work.

    Code:
    if(char[] == "I love cheese."){
    }
    Don't we wish!

    A char is a single letter or digit, so no go. Strings in C *must* be elevated to string status by the use of the end of string marker: '\0'.

    This:
    char *string = {"I love cheese"};

    has the end of string marker automatically applied to it. Certain string functions will do this, as well. scanf() and fscanf() are two that come first to mind. fgets() will, if there is room for it.

    Anyway, to compare strings in C:

    Code:
    if(strcmp(string1, string2) == 0)  //strings match
    if(strcmp(string1, string2)  > 0)  //string1 is greater
    if(strcmp(string1, string2)  < 0) //string2 is greater
    
    result = strcmp(string1, string2);  //can be used this way, as well
    if(result == 0)
       //strings are a match
    else if(result > 0)   //string1 is greater
    else
       //string2 is greater
    You'll need to include the header file <string.h>, (usually, compiler's vary) to use strcmp().

    If you only need to /want to compare the first N char's of each string, then you can use the "sister" function strncmp().

    Pretty spiffy, eh?

  3. #3
    Registered User
    Join Date
    Mar 2009
    Posts
    28
    This is da best C forum EVA!!!! Thanks man!

  4. #4
    C++まいる!Cをこわせ!
    Join Date
    Oct 2007
    Location
    Inside my computer
    Posts
    24,654
    Adak, why do you keep showing off string literals as non-const? Clearly, this is bad practice to teach newbies.
    Quote Originally Posted by Adak View Post
    io.h certainly IS included in some modern compilers. It is no longer part of the standard for C, but it is nevertheless, included in the very latest Pelles C versions.
    Quote Originally Posted by Salem View Post
    You mean it's included as a crutch to help ancient programmers limp along without them having to relearn too much.

    Outside of your DOS world, your header file is meaningless.

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. Code review
    By Elysia in forum C++ Programming
    Replies: 71
    Last Post: 05-13-2008, 09:42 PM
  2. Replies: 8
    Last Post: 04-25-2008, 02:45 PM
  3. Linked List Help
    By CJ7Mudrover in forum C Programming
    Replies: 9
    Last Post: 03-10-2004, 10:33 PM
  4. comparing fields in a text file
    By darfader in forum C Programming
    Replies: 9
    Last Post: 08-22-2003, 08:21 AM
  5. String sorthing, file opening and saving.
    By j0hnb in forum C Programming
    Replies: 9
    Last Post: 01-23-2003, 01:18 AM