频率字长,程序只打开cmd,但不做任何事,c++
Frequency of word length, program only opens the cmd, but does nothing, 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 Frequencyn";
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;
}
提前感谢。希望有人能帮忙。
尽管在NextWordLength
中声明了fin
,但您的函数从未使用它。相反,它从cin
中读取,因此您的程序期望您输入文本供其处理。