For goodness' sake, it's seems such a simple piece of code and I just can't figure out where I went wrong.
int count = 0;
for (int i = 0; i<10;i++){
if (chararray[i]=='\0' && i == 0){
cout << "Empty \n";
break;
}
if (chararray[i]!='\0') {
count = count ++;
}
}
cout << "Deleted " << count << "elements \n";
So the basic idea is that it goes through the array and if it's empty, then returns "Empty" and if not then it counts all the non empty cells and returns how many of them there were. If it makes any difference, I'm putting this under deconstructor method.
Generally it works fine, it just won't COUNT right. It either counts all or none.
UPDATE!
Thank you all! I removed the count = count++
line with ++count
and it displayed more correct results than before, but not for all test values (and I promise not to make this same mistake again). As it is, I took the advice to use strlen
function as there isn't a specific need for a 0 in place of, well, nothing. Also it made the code much, much shorter. Thank you!
You titled your question as
however as it is seen in the code snippet the count is increased when an element of the array is not equal to '\0'
So what is the empty char cell that you are going to count?
Take into acccount that this statement
has undefined behaviour because applying the side effect of operaator ++ is not sequenced relative to the left operand assignment.
If the array contains a string and you want to know whether it is empty and how many characters in the string then you should use standard C function
strlen
If the array does not contain a string and elements with value
'\0'
can be in any place of the array then that tp count non-zero elements you should use standard algorithmstd::count_if
For example