如何防止频率表计算C ++中的``空盒''

时间:2018-07-17 11:48:28

标签: c++

我编写了以下代码(用于家庭作业),该代码计算字母和数字并生成频率表。 我的问题是:在字母或数字不存在时如何停止频率生成

使用我编写的代码,该程序将对输入给它的每个字母进行计数,但还会为ASCII代码中的每个可能的字母/数字发布一行。

希望我的问题是对的,感谢您的帮助或建议!

#include <iostream>
#include <string>

using namespace std;

int countingLetters(string someWords);

int countingNumbers(string someWords);

int frequency(string someWords, double totalChar);

int main() {
    string someWords;
    cout << "Write a some words: " << endl;
    getline(cin, someWords);
    cout << "You wrote:" << someWords << '\n';

    cout << "Your sentence has " << someWords.length() << " characters." << '\n';

    double totalChar = someWords.length();

    cout << "Your sentence has " << countingLetters(someWords) << " letters." << '\n';

    cout << "Your sentence has " << countingNumbers(someWords) << " numbers." << '\n';

    cout << "Frequency of signs and letters :" << endl;

    frequency(someWords, totalChar);


    return 0;
}

int countingLetters(string someWords) {
    int count = 0;
    for (int i = 0; i < someWords.length(); i++) {
        if (someWords[i] >= 'a' && someWords[i] <= 'z')
            count++;
    }
    return count;
}

int countingNumbers(string someWords) {
    int count = 0;
    for (int i = 0; i < someWords.length(); i++) {
        if (isdigit(someWords[i]) != 0)
            count++;
    }
    return count;
}

int frequency(string someWords, double totalChar) {
    cout << " Letter" << '\t' << "Antal" << '\t' << "Procent" << endl;
    int frequency[255]={0};
    for (int i = 0; i < someWords.length(); i++) {
        char c = someWords[i];
        if (isdigit(c) != 0)
            frequency[c]++;
        if (isalpha(c) != 0)
            frequency[c]++;
    }
    for (int i = 0; i < sizeof(frequency); i++) {
        if(frequency[i]>0)
        cout << '\t' << static_cast<char>(i) << '\t' << frequency[i] << '\t' << frequency[i]/totalChar << endl;
    }

    return 0;
}

1 个答案:

答案 0 :(得分:1)

sizeof(frequency)frequency数组的大小,以字节为单位。您想要的元素数是将数组除以一个数组元素的字节数后得到的字节数:

这是frequency数组中元素的数量:

sizeof(frequency) / sizeof(frequency[0])

但是在使用C ++时,您不应使用原始数组,而应使用std::array

#include <array>
...
int frequency(string someWords, int totalChar) {
  cout << " Letter" << '\t' << "Antal" << '\t' << "Procent" << endl;
  std::array<int, 255> frequency{0};

  for (int i = 0; i < someWords.length(); i++) {
    char c = someWords[i];
    if (isdigit(c) != 0)
      frequency[c]++;
    if (isalpha(c) != 0)
      frequency[c]++;
  }

  int x = frequency.max_size();

  for (int i = 0; i < frequency.max_size(); i++) {
    if (frequency[i]>0)
      cout << '\t' << static_cast<char>(i) << '\t' << frequency[i] << '\t' << frequency[i] / totalChar << endl;
  }

  return 0;
}

仍有改进的空间。