简体   繁体   中英

C++ Char checking gives outrageous value

i am trying to make a program to check and list the genders of a number of student, m being fem and l being male. I'm not sure what's wrong with my code but when i print out the m and l variable they have either really huge. Have been trying to solve this for hours, your help is greatly appreciated, cheers.

PS sorry for my bad english.

 #include<iostream>
#include<string>
using namespace std;
main()
{
char gender[20];
int jlh,i,j,m,l;

cin>>jlh;
system("cls");
for(i=0;i<jlh;i++)
{   cout<<"Data "<<i+1<<endl;
    cout<<"Enter your gender - "<<endl;
    cin>>gender[i];
}

m,l=0;
for(i=0;i<jlh;i++){
    if(gender[i]=='p'){
        m=m+1;
    }
    else if(gender[i]=='l'){
        l=l+1;
    }
    }
    cout<<endl<<l<<endl;
    cout<<m;
 }

The line

m,l=0;

does not work as you expect. Look up the comma operator , it evaluates the first operand (just m in this case), discards the result, and evaluates and returns the second operand. So only l is set to zero. I would recommend moving the declaration to this line and initializing the variables in one go, like so

int m=0, l=0;
for (int i=0; i<jlh; i++) 
  ...

I would also move the declaration of variables like i to where they are needed, as shown above; there is no need to put all declaration at the beginning of the function.

Then the output

cout<<endl<<l<<endl;
cout<<m;

places the endl before and after the first variable, but not after the second. You should have an endl after the last line of your output, otherwise your console prompt is right after your value. It would improve readability to have something like this:

std::cout << "Number of females: " << m << std::endl; 
std::cout << "Number of males:   " << l << std::endl;

You should also make sure that not more than 20 values are entered, as your array has this size. But there is not even a need for this (maybe there is in your real code, but not in the MCVE): You can just increment the variables when reading the input, no need to store it in the array. This gets rid off this arbitrary limit. If you really need the values, you should use a std::vector instead of a fixed size array.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM