简体   繁体   中英

c++ work around comparison between pointer and integer

do {
    getline (myfile,temp);
    if (temp[0] != "="){
        MyAlbums[i].tracks.push_back(temp);

    }
    else {
        break;
    }
}while(true);

gives me this error:

ISO C++ forbids comparison between pointer and integer [-fpermissive]

i am trying to loop through lines in a text file and 'push_pack' if the line does not begin with an "=" equals character. else i want to break out of the loop.

Any help is very much appriceated!

if (temp[0] != "="){

should be

if (temp[0] != '='){

The reason is that temp[0] is of type char (assume temp is the string you read in), you should compare it with char literal '=' not string literal "=" . I am assuming that you read temp successfully, so you may need to check for that if this is not the case.

EDIT (thanks Adam Liss)

strings literals like "=" are of ( const char * ) type, they are enclosed in double-quotes; individual characters are enclosed in single-quotes. therefore, you have that compile complain message about comparing a char (char literal are integers) with const char * .

Quoting from here: IBM C++ documentation

C  A character literal has type int.
C++ A character literal that contains only one character has type char, 
which is an integral type.

First, make sure that getline succeeded. Evaluate it in a bool ean context to figure that out:

while (getline(myfile, temp)) {
  /* code goes here */
}

instead of

do {
  getline(myfile, temp);
  /* code goes here */
} while (true);

Never, ever do input without checking if it failed immediately, or you will get really annoying bugs to track down.

Second, make sure temp is at least 1 character long. temp.size() >= 1 will be true if it is safe to do temp[0] . If getline ever gives you a string of length 0, doing temp[0] on it will result in undefined behavior. Undefined behavior is really annoying to track down, because it can behave completely innocuous in one situation, and then bite you in an unexpected place later.

Third, do temp[0] != '=' instead of temp[0] != "=" . '=' is a character, "=" is a buffer of 2 characters the first one is '=' the second is '\\0' . The array of two characters denoted by "=" is implicitly converted into a pointer to the first character when you try to do != , which then generates an error (because it has no idea how to compare a pointer to a character to a character).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM