C 计数字符来自文本文件,无论情况如何

C++ Counting character occurrence from a text file regardless of case

本文关键字:情况 文件 文本 数字 字符      更新时间:2023-10-16

在C 中,我试图从文件中获取文本并计算字符的出现,而忽略了差异。到目前为止,我可以做到这一点而无需忽略案件。

map<char, size_t> char_count;
char character;
while (myfile >> character)
    ++char_count[character];   // fetch and increment the counter for word
for (const auto &w : char_count) // for each element in the map
    // print the results
    cout <<  w.first << " occurs " << w.second
         << ((w.second > 1) ? " times" : " time") << endl;

我的解决方案将是:

character = tolower(character)

,但是tolower()不会接受char,只有一个int。有任何想法吗?我是以错误的方式接近这个问题吗?

是的,您可以使用tolower将字符转换为小写,我已经修改了您的代码,希望它可以帮助您:

while (myfile >> character)
    ++char_count[tolower(character)];

您的解决方案适用。
只需使用tolower并将char转换为int。

相关文章: