[英]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'
和'\\0'
。
'\\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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.