通读文件中的字符并计算有多少单个字母[c ++]

时间:2015-04-30 17:38:08

标签: c++ char ifstream

因此用户将输入一个包含任何文本的文件,程序需要读取每个字符并计算每个字符的数量(仅限大写和小写字母)。那么,可能有50个A,23个等等......

以下是我在main.cc中的内容:

    char character;
    int i = 65; //this is the iterator to go through upper and lowercase letters
    int count = 0; //counts number of characters and resets when exiting the loop and after using cout
    ifstream file(filename); //filename is a string the user inputs
    while (i != 0) {
        while (file >> character) {
            int a = character;
            cout << a << endl; //testing: outputs the correct number for the letter
            if (i == a) { //but for some reason this part isn't working?
                count++;
            }
        }
        cout << count << endl; //this outputs 0 every time
        count = 0;
        i++;
        if (i == 91)  i = 97;  //switch to lower case
        if (i == 123) i = 0;   //exit loop
    }

感谢您的帮助!谢谢:))

2 个答案:

答案 0 :(得分:3)

假设文本是ASCII或扩展ASCII,因此最多可能有256个字符。

您可以使用数组来保存给定字符的出现次数。每个插槽对应一个字符;相反,该字符可以用作数组的索引。

示例:

unsigned int MAXIMUM_CHAR_VALUES = 256U;
unsigned int occurrences[MAXIMUM_CHAR_VALUES] = {0};
char c;
while (my_text_file >> c)
{
  ++occurrences[c];
}
// Print them out
for (unsigned int i = 0; i < MAXIMUM_CHAR_VALUES; ++i)
{
  if (!isprint(i))
  {
    cout << "0x" << hex << i;
  }
  else 
  {
    c = static_cast<char>(i);
    cout << c;
  }
  cout << ":  " << occurrences[i] << "\n";
}

如果必须使用“节点”,则可以将阵列更改为节点数组。

还可以使用其他结构,例如二叉树。

答案 1 :(得分:2)

这是使用地图的理想场所

从文件中读取一个字符

file >> character;

地图位置的增量

if( isalpha(character) ) { myMap[character]++; }

最后,您可以遍历所有地图条目并将其全部打印出来。

for(map<char, int >::const_iterator it = myMap.begin(); it != myMap.end(); ++it)
{    
    std::cout << "The character " << it->first << " was found " << it->second<< " times." << std::endl;
}