C ++:计算文件中ASCII字符的频率 [英] C++: Counting the frequency of ASCII characters in file

查看:146
本文介绍了C ++:计算文件中ASCII字符的频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我是C ++的初学者,已经思考了很长时间了,但是我发现自己无法提出解决方案,并希望在这里可以找到一些方向.

I am a beginner to C++ and have been pondering this problem for quite a while, but I'm finding myself unable to come up with a solution and was hoping I could find some direction here.

我有一个输入文件,其中将包含任意数量的ASCII字符(例如:hello,world,lorem ipsum等).我的程序将读取该文件并计算每个ASCII字符的频率,并在达到EOF时输出结束计数.我相信我需要将array [128]用于计数器,但是除此之外,我完全陷入了困境.

I have an input file that will contain any number of ASCII characters (ex: hello, world; lorem ipsum; etc.). My program will read this file and count the frequency of each ASCII character, outputting the end counts when EOF is reached. I believe I need to use array[128] for the counters, but besides that, I'm totally stuck.

这是我到目前为止所拥有的(数量不多,仅从文件中读取字符):

Here's what I have so far (it's not much and only reads the characters from the file):

#include <iostream>
#include <fstream>
#include <string>
#include <cstdlib>
using namespace std;

int main(void)
{
    ifstream inputFile;
    string infile;
    char ch;
    //char ascii;
    //int asciiArray[128] = {0};

    // Gets input filename from user, checks to make sure it can be opened, and then
    // gets output filename from user.
    cout << "Please enter your input filename: ";
    cin >> infile;

    inputFile.open(infile.c_str());

    if (inputFile.fail())
    {
        cout << "Input file could not be opened. Try again." << endl;
        exit(0);
    }

    // Gets the first character of the input file.
    inputFile.get(ch);

    while(!inputFile.eof())
    {
        inputFile.get(ch);
    }

    // Closes the input file
    inputFile.close();

    return 0;
}

任何方向或帮助将不胜感激.我有一种感觉,我将需要使用指针来解决这个问题……但是我才刚刚开始涉及指针,所以我很困惑.谢谢!

Any direction or help would be greatly appreciated. I have a feeling I will need to use pointers to solve this...but I've just barely started covering pointers, so I'm very confused. Thanks!

我删除了一些变量,并且现在可以正常工作,好像在集思广益时忘记了这些变量.对不起,它不起作用并且没有提及原因;我不会再这样做了!

I removed some variables and it's working now, looks like I forgot them there while I was brainstorming. Sorry for leaving it unworking and not mentioning why; I won't do that again!

推荐答案

您应将循环编写为:

while(inputFile >> ascii)
{                    
    asciiArray[ascii]++;
}

请注意,由于循环几乎总是错误的,因此我不会在循环条件下直接检查eof.

Note that I don't directly check for eof in the loop condition since that's almost always wrong.

此外,您还应该确保文件确实只用ascii字符编写.由于任何不在ASCII范围内的字符都将导致对asciiArray的无限制访问.

Also you should be sure that your file is indeed written with ascii characters only. Since any character outside the ascii range would result in an out of bounds access to the asciiArray.

这篇关于C ++:计算文件中ASCII字符的频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆