-1

I want to print a dynamic char array which has \0 characters before the actual end. I am printing it by using cout for every index.

for (int i = 0; i < size; i++) {

        std::cout << content[i];
}

But when I come by a \0 character I want to detect it, so I'm using:

if (content[i] == 0) {
     std::cout "zero";
}

I tried to do

if (content[i] == "\0") {
     std::cout "zero";
}

But I can't do that comparison because you apparently cannot compare a const char* and a char.

What did I do wrong? How do I make this comparison?

char array btw:

char * content = new char[size];
file.seekg(0);
file.read(content, size);
user4581301
  • 33,082
  • 7
  • 33
  • 54
  • 1
    `content[i] == 0` compares a `char` and an `int`. What specifically is giving you said error? – chris Jun 26 '19 at 17:25
  • Post a [mcve] as required here please! ([Edit] your question) – πάντα ῥεῖ Jun 26 '19 at 17:29
  • 1
    `content[i] == 0` is correct, so whatever problem you are having, it's not that. There's some other issue with your code and you're only making things worse by trying to fix the wrong thing (common newbie situation). Posting a complete program illustrating your problem instead of just snippetts would help. – john Jun 26 '19 at 17:37
  • Perhaps [this question](https://stackoverflow.com/questions/3683602/single-quotes-vs-double-quotes-in-c-or-c) helps? – chris Jun 26 '19 at 17:38

2 Answers2

4

in

if (content[i] == "\0")

the "\0" is a string literal, a const char [2] in this case. This decays to a pointer, resulting in a const char * being compared with a char and the compiler error.

You want

if (content[i] == '\0')

to get a null as a character. That said, integers can compare against char, so if (content[i] == 0) is valid, but (my opinion) less clear than explicitly making a null character.

Further reading: Single quotes vs. double quotes in C or C++ (chris provided the link)

user4581301
  • 33,082
  • 7
  • 33
  • 54
-4

Try "0" in you if-statement, since then you would be comparing the same types

πάντα ῥεῖ
  • 1
  • 13
  • 116
  • 190
Xander
  • 57
  • 3