计算文本文件中的单个字母并打印结果 - 错误的输出 C++

Counting Individual Letters In Text File & Print Results -Wrong Output c++

本文关键字:结果 错误 C++ 输出 打印 文件 文本 单个字 计算      更新时间:2023-10-16

我正在尝试从命令行读取一个文件,将字符读取到数组中,计算字符的个性并打印结果。代码编译时没有任何错误,但单个字母的计数远高于大文件的计数,有时对小文件根本不计数。

#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;
}