Search code examples
c++stringcharcounter

Why is the counter value not incrementing?


The counter does not increase at all so I want to know which part went wrong.

#include <cstring>
#include <iostream>
using namespace std;


            
int main(){
   int total=0,na=0,ni=0;//use to count how much type of element is there
   string chem;
   getline(cin,chem);

   for(int i=0;i!='\0';i++){
       if(chem[i]=='N'){
           if(chem[i+1]=='i'){
               ni++;
           }else{
              na++;
              cout<<na<<endl;
        }
    }
}

na and total values are both 0

cout<<na<<endl;
total=total + ni+na;
cout<<total;

Solution

  • for(int i=0;i!='\0';i++){
    

    is the same as

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

    ('\0' is a char type with value 0).

    The conditional check means the loop body never runs.