计算文件流中的字符
Counting characters in a file stream
我正在尝试创建一个函数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;
相关文章:
- 将字符指针十六进制转换为字符串并保存在文本文件C++中
- 如何在C++中确定文本文件中的元素是字符还是数字
- 如何在 C++ 中从文件中读取字符数组(带有一些空格)
- 如何从文本文件中读取数值,直到遇到字符类型?
- 使用 fopen 打开 .pak 文件并使该文件应用于 const 无符号字符* (C++)
- 如何像在 C++ 中处理数组一样对 .txt 文件中的字符进行寻址?
- 尝试将字符串从文件读取到无符号字符向量中
- 如何在C++中反转文本文件中字符的顺序?
- 生成随机.txt文件,10行,10列。充满随机:"*"、"#"、"@"。然后将随机字符替换为'P'
- 如何存储 unicode 字符并将其输出到文件?
- 无法将整个文本文件复制到字符数组
- 仅读取文件末尾的最后 3 个字符,并将其另存为 int
- 将未签名的字符写入输出文件
- 从我的 2DgridArray 中的文本文件中获取每个字符
- ifstream 读取的字符与文件中写入的字符不同
- VSCode C++调试文件名中包含中文字符的文件时插件损坏
- 从文本文件 (C++) 生成字符矩阵
- 使用指针编译代码后,.cpp文件将变为随机字符
- 在c++中读取文件时,它如何自动将字符放入字符数组,将数字放入整数变量
- 跨平台UTF-8字符文件数据编码/解码