c++ - 如何计算每次读入一个字符的个数?

标签 c++ string file io floating-point

我是 C++ 类的学生。我需要帮助完成一项任务。

"Read from a text file called salaries.txt that contains the following format:

M321232.34
F43234.34
M23432.23
M191929.34

字母“M”和“F”代表性别,数字代表 他们的薪水。每次读一个时数一数男性的数量,并且 将每个男性工资加到累计的 totalMaleSalary 中。做同样的 女性。在循环结束时计算女性平均工资 和平均男性工资 - 显示您的结果并确定 两个平均值中哪个更大。”

我如何计算男性人数并添加每个人的薪水?

这是我的:

int main(){

    int male=0, female=0;
    double salary,totalMaleSalary=0,totalFemaleSalary=0;
    char gender;

    ifstream fin;
    fin.open("salary.txt");
    do{
        fin>>gender>>salary;
        if(gender=='M'){
            male=male+1;
            totalMaleSalary=salary+totalMaleSalary;
        }
        if(gender=='F'){
            female=female+1;
            totalFemaleSalary=salary+totalFemaleSalary;
        }

        cout<<"Number of Males is "<<male<<endl;
        cout<<"Number of Females is "<<female<<endl;
        cout<<"Total Male Salary is "<<totalMaleSalary<<endl;
        cout<<"Total Female Salary is "<<totalFemaleSalary<<endl;
        cout<<"Average Male salary is "<<totalMaleSalary/male<<endl;
        cout<<"Average Female salary is "<<totalMaleSalary/female<<endl;

    }while(!fin.eof());


    fin.close();
    return 0;
}

最佳答案

  1. 不要假定文件已成功打开。使用 if ( !is )... .
  2. 不要使用 eof() .提取成功时读取:while ( is >>... .
  3. 读取整个文件后必须显示结果:cout <<...必须在外循环。

你的固定程序:

#include <iostream>
#include <fstream>

using namespace std;

int main() 
{
  std::ifstream is( "salary.txt" );
  if ( !is )
    return -1; // failed to open

  int male = 0, female = 0;
  double salary, totalMaleSalary = 0, totalFemaleSalary = 0;
  char gender;

  while ( is >> gender >> salary )
  {
    if ( gender == 'M' )
    {
      male = male + 1;
      totalMaleSalary = salary + totalMaleSalary;
    }
    else if ( gender == 'F' )
    {
      female = female + 1;
      totalFemaleSalary = salary + totalFemaleSalary;
    }
    else
      return -2; // unknown
  };

  cout << "Number of Males is " << male << endl;
  cout << "Number of Females is " << female << endl;
  cout << "Total Male Salary is " << totalMaleSalary << endl;
  cout << "Total Female Salary is " << totalFemaleSalary << endl;
  cout << "Average Male salary is " << totalMaleSalary / male << endl;
  cout << "Average Female salary is " << totalMaleSalary / female << endl;

  return 0;
}

关于c++ - 如何计算每次读入一个字符的个数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47467570/

相关文章:

c++ - std::vector 的引用

c++ - Boost 数值常量优点

c++ - 什么是代表?

python - python中字符串的上下文相关拆分

c# - 如何将所有转换为一个字符串?

java - 为什么我的 while 循环不停止?

c++ - 函数参数的声明区域

c - 需要帮助 : Unable to delete string from doubly linked list: C

c - 创建文件的自定义 header (元数据)

javascript - 使用 .js 和 .jsx 作为 Reactjs 的文件结尾有什么区别?