Thread: Why doesn't this work?

  1. #1
    Registered User
    Join Date
    Feb 2010

    Smile Why doesn't this work?


    int main()
        string str;
        str = "01";
        if(str[0] == "0")
            cout << "Equal";
    ISO C++ forbids comparison between pointer and integer

    How does one make it so that str[0] refers to the actual character with a string datatype to it?

  2. #2
    Registered User
    Join Date
    Jul 2010
    "0" is a C-style string, not a char. Use single quotes for char - '0'.

  3. #3
    Join Date
    Oct 2007
    Inside my computer
    This error message is a bit misleading. But it makes perfect sense. Here's what happens:
    [0] fetches a specific element of the string, a character, which is of type char. The char is promoted to an integer before being compared.
    "0" is a C-style string, an array of two chars, which decays to a pointer const char*.
    So in the end, you try to compare an int with a const char* and that is why the compiler complains the way it does.
    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. strcmp returning 1...
    By Axel in forum C Programming
    Replies: 12
    Last Post: 09-08-2006, 07:48 PM
  2. getline() don't want to work anymore...
    By mikahell in forum C++ Programming
    Replies: 7
    Last Post: 07-31-2006, 10:50 AM
  3. Why don't the tutorials on this site work on my computer?
    By jsrig88 in forum C++ Programming
    Replies: 3
    Last Post: 05-15-2006, 10:39 PM
  4. fopen();
    By GanglyLamb in forum C Programming
    Replies: 8
    Last Post: 11-03-2002, 12:39 PM
  5. DLL __cdecl doesnt seem to work?
    By Xei in forum C++ Programming
    Replies: 6
    Last Post: 08-21-2002, 04:36 PM