Home > Back-end >  How do I make pass and fail count work in c ?
How do I make pass and fail count work in c ?

Time:10-04

I'm working on this function for one of my classes and my pass count works just fine, however, my fail count ALWAYS prints out 12. I've been reading my code top to bottom and just can't seem to find the problem.

#include <iostream>
#include <sstream>
#include <string>
   
using namespace std;
 
string passAndFailCount(string grades){
  int pass_count;
  int fail_count;
  istringstream myStream(grades);
  string grade;
  while(myStream>>grade){
    int i_grade=stoi(grade);
    if (i_grade>=55){
        pass_count;
    }
    else{
        fail_count;
    }
  }
  cout<<"Pass: "<<pass_count<<endl<<"Fail: "<<fail_count<<endl;
}

int main()
{
  string grades;
  getline(cin, grades);
  passAndFailCount(grades);
}

CodePudding user response:

Your problem are uninitialized variables.

int pass_count = 0;
int fail_count = 0;

and you're set.

For an explanation. Non-global variables (which automatically get initialized to 'default' (0) as per the standard), automatic and dynamic variables (like the one you are using), assume the value of 'whatever was in memory at the time of allocating the variable'.

Memory is never empty, there's always 'something' written in there.

So the memory of your fail_count variable just 'happened to be' 12 during allocation, which is why you start with that value. This value can be anything within scope.

By explicitly assigning a variable, you 'initialize' the variable, putting it into a defined state (0) and your program should start working as expected.

  •  Tags:  
  • c
  • Related