计算文件流中的字符

Counting characters in a file stream

本文关键字:字符 文件 计算      更新时间:2023-10-16

我正在尝试创建一个函数how_many(),它计算文件流中某种类型的字符数量,例如"n"或","。这是我(失败的)尝试:

int how_many(char mychar, anifstream myfile){
    int result;
    while(!myfile.eof())
    {
       if(myfile.get()==mychar){result=result+1;}
    }
    myfile.close(); // Closes the filestream "my file"
    return result; 
}

第一个问题:"n"是字符还是字符串?(如果是这样,那么我应该将第一个输入设置为字符串而不是字符)

第二个问题:你能解释一下产生的错误信息吗?(或者直接指出我代码中的语法错误):

 warning: result of comparison against a string literal is unspecified
  (use strncmp instead) [-Wstring-compare]
 note: candidate function not viable: no known conversion from 'const char [2]' to
  'char' for 1st argument

"n"是类型为const char[2]的字符串字面值,包含两个字符:'n'''

'n' -是类型为char的转义字符。

考虑变量result在你的函数中没有初始化

'n'是字符,而"n"是字符串字面值(类型为const char[2]最后一个为null)

用于计数首选算法

#include <algorithm>
#include <iterator>
//..
std::size_t result = std::count( std::istream_iterator<char>(myfile), 
                                 std::istream_iterator<char>(),
                                  mychar 
                                ) ;

在读取文件时,您可能想要制作一个直方图:

std::vector<char> character_counts(256); // Assuming ASCII characters
// ...
char c;
while (cin >> c) // The proper way to read in a character and check for eof
{
  character_counts[c]++; // Increment the number of occurances of the character.
}

在您发布的情况下,您可以通过以下方式找到'n'的数量:

cout << "Number of '\n' is: " << character_counts['n'] << endl;