Home > Enterprise >  Count variable is not incrementing properly
Count variable is not incrementing properly

Time:09-10

#include <bits/stdc  .h>
using namespace std;
int main(){
    string arr[8];
    
    
    for(int i=0;i<8;i  ){
        cin>>arr[i];
    }
    int count=0;
    for(int i=0;i<8;i  ){
        if(arr[i]== "JAVA"){
            count =1;
        }


    }
    
        
    
    cout<<"JAVA lecture is repeating"<<" "<<count<<" "<<"times";
}

It is printing: "JAVA lecture is repeating 2 times" instead of "JAVA lecture is repeating 4 times", for sample input of: "JAVA JAVA DataStructures DBMS JAVA JAVA Python DataStructures"

output image

CodePudding user response:

I tested the code, it DOES output the result 4 as we expected.

the output image

CodePudding user response:

You might wanna do something like this instead.

#include <bits/stdc  .h>
using namespace std;

int main(){
    string str,word;
    getline(cin,str);
    getline(cin,word);

    stringstream ss(str);
    int cnt=0;
    while(ss>>str){
        if(str==word)
          cnt  ;
    }
    cout<<cnt<<"\n";
    return 0;
}
  • Related