C ++计算文件中的小写字符,大写字符和数字

时间:2016-02-28 02:53:38

标签: c++ string

我正在学习编程,我的一项任务是创建一个程序,以便计算任何类型的输入文本文件中的大写,小写和数字的数量。出于某种原因,在我的程序中,它已经确认被计数的小写字母的数量是一个非常大的数字。我不知道如何解决这个问题。大写和数字的计数似乎工作正常。另外,我对C ++知之甚少,所以请不要把任何太高级的东西放在前面,抱歉。

#include <iostream>
#include <fstream>
#include <cstring>
using namespace std;

void countfile(char *a, int &x, int &y, int &z)
{

  int len = strlen(a);
  for (int i =0; i < len; i++)
  {
    for (char b = 'A'; b <= 'Z'; b++)
    {
      if (a[i] == b)
        x++;
    }
  }
  for (int i = 0; i < len; i++)
  {
    for (char b = 'a'; b <= 'z'; b++)
    {
      if (a[i] == b)
        y++;
    }
  }
  for (int i =0; i < len; i++)
  {
    for (char b = '0'; b <= '9'; b++)
    {
      if (a[i] == b)
        z++;
    }
  }
}
int main()
{
  string fileName;
  ifstream fin;
  cout << "Enter a text file: ";
  getline(cin, fileName);
  fin.open(fileName.c_str());
  if (!fin.good()) throw "I/O error";
  int uppercount, lowercount, digitcount;
  while (true)
  {
    string s;
    getline(fin, s);
    char *a = new char[s.size()+1];
    a = (char*)s.c_str();
    if (!fin.good()) break;
    countfile(a, uppercount, lowercount, digitcount);
  }
  cout << "The file contains: " << endl;
  cout << uppercount << " uppercase letters" << endl;
  cout << lowercount << " lowercase letters" << endl;
  cout << digitcount << " digits" << endl;
  return 0;
}

1 个答案:

答案 0 :(得分:1)

您必须初始化变量。

//#define USE_UNITS
//#define USE_RAW

typedef struct {
    uint8_t alarm_num;
    uint8_t dec;
    boolean sign;
    PGM_P label;
    PGM_P label_suffix;
#ifdef  USE_UNITS
    PGM_P units;
#define X_UNITS(x) x,
#else
#define X_UNITS(x)
#endif
#ifdef  USE_RAW
    boolean raw;
#define X_RAW(x) x,
#else
#define X_RAW(x)
#endif
    boolean newline;
} TEST_TABLE_TYPE;

const TEST_TABLE_TYPE PROGMEM test_table[NUM_ALARMS] = {
  { ALARM_VIN_UV_LVL, MEAS_VIN_VCAP_VOUT_DEC, false, label_vin_string, 
    label_uv_string, X_UNITS(units_volts_string) X_RAW(false) false },
  { ALARM_VIN_OV_LVL, MEAS_VIN_VCAP_VOUT_DEC, false, label_vin_string,
    label_ov_string, X_UNITS(units_volts_string) X_RAW(false) false },
  { ALARM_IIN_OC_LVL, MEAS_IIN_ICHG_DEC, true, label_iin_string, 
    label_oc_string, X_UNITS(units_amps_string) X_RAW(false) true },
  { ALARM_VOUT_UV_LVL, MEAS_VIN_VCAP_VOUT_DEC, false, label_vout_string,
    label_uv_string, X_UNITS(units_volts_string) X_RAW(false) false }
};

您可能会收到编译器警告,除非您按地址传递它们,并且编译器不知道您将如何处理它们。