-1

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;
Big Yong
  • 23
  • 3
  • 4
    `i!='\0'` will be immediatly false, and you won't even do one iteration of the loop. – wohlstad Aug 08 '22 at 07:22
  • I think your loop doesn't even do an iteration. Check your for expression. – Joost00719 Aug 08 '22 at 07:23
  • Use a debugger. And refer to [What is a debugger and how can it help me diagnose problems?](https://stackoverflow.com/questions/25385173/what-is-a-debugger-and-how-can-it-help-me-diagnose-problems). – Jason Aug 08 '22 at 07:25
  • `for (int i = 0; i != '\0'; i++)` initialises `i` to zero, then only iterates if `i` is non-zero. Which means it doesn't iterate at all. – Peter Aug 08 '22 at 07:26
  • Because this is just like `for(int i=0;i!=0;i++){}` – qrsngky Aug 08 '22 at 07:26
  • Presumably you meant this `for(int i=0;chem[i]!='\0';i++){` – john Aug 08 '22 at 07:51

1 Answers1

0
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.

Bathsheba
  • 231,907
  • 34
  • 361
  • 483