计算文本文件中的单个字母并打印结果 - 错误的输出 C++
Counting Individual Letters In Text File & Print Results -Wrong Output c++
我正在尝试从命令行读取一个文件,将字符读取到数组中,计算字符的个性并打印结果。代码编译时没有任何错误,但单个字母的计数远高于大文件的计数,有时对小文件根本不计数。
#include <iostream>
#include <fstream>
#include <string.h>
#include <cctype>
#include <algorithm>
using namespace std;
int main(int argc, char **argv){
if(argc !=2){
cout << "usage: " << argv[0] << " <filename>n";
}
else{
ifstream myfile (argv[1]);
if(!myfile.is_open()) //check to see if file is opened.
cout << "Can not open your filen";
else{
static int array[26]; //stores the frequency of letters.
char t;
while(!myfile.eof()){
while(myfile.get(t)){
if(isupper(t)){
int i = 0;
do{
array[tolower(t)-'a']++;
i++;
}
while(i < 26);
}
}
int x = 0;
while(x < 26){
cout << 'a' + x << ":" << array[x] << endl;
x++;
}
}
}
}
return 0;
}
问题是myfile.get(t)
,它从流中提取一个字符并将其放入t
。现在,如果读取的字符恰好是大写,则在数组上迭代26次,递增其小写字母计数。你只需要做一次。
此外,您还需要处理输入流中的非alpha字符。
while(!myfile.eof()){
myfile.get(t);
if(isalpha(t) { // process only alphabets.
if(isupper(t)) // convert upper case to lower case
t = tolower(t);
array[t-'a']++; // increment the count
}
}
这不接受命令行上的文件名(只处理其标准输入),但可能会为更简单的通用方法提供一些灵感:
#include <ctype.h>
#include <iostream>
#include <vector>
#include <fstream>
#include <iterator>
#include <algorithm>
int main() {
std::vector<size_t> freqs(26);
std::for_each(std::istream_iterator<char>(std::cin),
std::istream_iterator<char>(),
[&](char ch) { if(isalpha(ch)) ++freqs[tolower(ch)-'a']; });
for (int i=0; i<26; i++)
std::cout << (char)('a'+i) << ":" << freqs[i] << "n";
return 0;
}
相关文章:
- 在没有定义返回类型的函数中返回布尔值,并将结果保存在无错误的char编译中-为什么
- C++ 随机数生成器:尝试将结果作为向量获取,但通过制作 void 函数来执行此操作而出现错误
- Static_cast转换为错误的数据类型,但结果仍然正确?
- C++ 犰狳库中的sort_index()函数给出了错误的结果
- C++:使用类在向量中搜索特定元素时,我得到了错误的结果
- 检查 n2 是否是 n1 的倍数后结果错误,但根本没有错误
- 为什么我的性能基准给了我错误的结果?
- 使用具有默认参数的函数模板进行 decltype 会使结果混乱(一个有趣的问题或 gcc 的错误)
- 斐波那契检验(C++)的结果错误
- 在发布版本中划分两个双精度的结果错误
- 2D FFT后的图像结果错误
- 计算文本文件中的单个字母并打印结果 - 错误的输出 C++
- C++字符和 int 之间的转换,结果错误
- char*与std字符串的比较结果错误
- 斯波吉购物结果错误
- 超载"+"操作员,结果错误?
- 执行高斯消去程序时结果错误
- hash_djb2 PHP结果错误
- 按位操作比较结果错误
- 使用'if'语句和"<<"时的结果错误,'>>'运算符比较 3 个整数