简体   繁体   English

C ++字符检查提供了惊人的价值

[英]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. 我正在尝试制作一个程序来检查和列出一些学生的性别,其中m是女性,l是男性。 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. 我不确定我的代码有什么问题,但是当我打印出m和l变量时,它们要么真的很大。 Have been trying to solve this for hours, your help is greatly appreciated, cheers. 尝试解决这个问题已有几个小时,非常感谢您的帮助,欢呼。

PS sorry for my bad english. PS对不起,我的英语不好。

 #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. 查找逗号运算符 ,它计算第一个操作数(在这种情况下为m ),舍弃结果,然后求值并返回第二个操作数。 So only l is set to zero. 因此只有l设置为零。 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; 我还将把像i这样的变量的声明移动到需要它们的地方,如上所述。 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. endl放在第一个变量之前和之后,但不能放在第二个变量之后。 You should have an endl after the last line of your output, otherwise your console prompt is right after your value. 您应该在输出的最后一行之后有一个endl ,否则控制台提示符就在您的值之后。 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. 您还应确保输入的值不超过20个,因为您的数组具有此大小。 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. 但是甚至不需要它(也许在您的真实代码中,而在MCVE中却没有):您可以在读取输入时增加变量,而无需将其存储在数组中。 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. 如果确实需要这些值,则应使用std::vector而不是固定大小的数组。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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