字长的频率,程序只打开cmd,但什么都不做,C ++

时间:2014-06-26 17:04:01

标签: c++

我一直在做作业很长一段时间。我已经尝试了很多解决方案,但我无法找到一种方法来使其工作。我的任务是创建一个代码,从文件中读取文本并显示单词长度的频率。也就是说,如果它读入“我的名字是Jon”,它应该显示“1 = 0,2 = 2,3 = 1,4 = 1”(第一个数字是单词的长度,第二个数字是频率)。我已经编写了一个代码,我非常确定它已经接近工作了,但它不起作用,它甚至没有显示错误或什么都没有,它只是打开cmd并且什么都不做。这是我的代码:

#include <iostream>
#include <ctype.h>
#include <iomanip>
#include <fstream>

using namespace std;

int NextWordLength(void); //function prototypes
void DisplayFrequencyTable(const int Words[]);

const int WORD_LENGTH = 16; // global constant for array

int main()
{
    int WordLength;  //actual length of word 0 to x
    int NumOfWords[WORD_LENGTH] = {0}; //array hold # of lengths of words

    WordLength=NextWordLength();
    while (WordLength)  //continue to loop until no word i.e. 0
    {
        (WordLength <= 14) ? (++NumOfWords[WordLength]):(++NumOfWords[15]);
        WordLength=NextWordLength();
    }
    DisplayFrequencyTable(NumOfWords);
}

int NextWordLength(void)
{
    fstream fin ("in.txt", ios::in);
    char Ch;
    int EndOfWord = 0; //tells when we have read in one word
    int LengthOfWord = 0;

    Ch = cin.get();  //get first character

    while (!cin.eof() && !EndOfWord)
    {
        while (isspace(Ch) || ispunct(Ch)) //skips elading white spaces
        {
            Ch = cin.get(); //and leading punctation marks
        }
        if (isalnum(Ch)) // if character is a letter or number
        {
            ++LengthOfWord;
        }
        Ch = cin.get(); //get next character
        if((Ch=='-')&&(cin.peek()=='\n')) //check for hyphenated word over two lines
        {
            Ch = cin.get();
            Ch = cin.get();

        }
        if ((Ch=='-')&&(isalpha(cin.peek()))) // check for hyphenated word in one line
        {
            ++LengthOfWord; //count the hyphen as part of word
            Ch = cin.get(); //get next character
        }
        if((Ch=='\n')&& (isalpha(cin.peek()))) //check for apostrophe in the word
        {
            ++LengthOfWord; //count apostrophe in word length
            Ch = cin.get(); //and get the next letter
        }
        if(isspace(Ch) || ispunct(Ch) || cin.eof()) //is it end of word
        {
            EndOfWord++;
        }
    }
    return LengthOfWord;
}


void DisplayFrequencyTable(const int Words[])
{
    int TotalWords = 0, TotalLength = 0;
    cout << "\nWord Length Frequency\n";
    cout << "------------ ----------\n";

    for (int i=1; i<=WORD_LENGTH-1; i++)
    {
        cout << setw(4)<<i<<setw(18)<<Words[i]<<endl;
        TotalLength += (i*Words[i]);
        TotalWords += Words[i];
    }
    cout << "\nAverage word length is ";

    if (TotalLength)
    {
        cout << float(TotalLength)/TotalWords << endl;
    }
    else cout << 0 << endl;
}

提前致谢。希望有人可以提供帮助。

1 个答案:

答案 0 :(得分:2)

尽管在fin中声明了NextWordLength,但您的功能从未使用过它。相反,它从cin读取,因此您的程序希望您键入文本以供处理。