我正在尝试使用以下函数计算文件中的字符数和行数。
void characterCount(ifstream& inf, string fName, int length [])
{
int charNum = 0;
int lineNum = 0;
char character;
inf.get(character);
while (!inf.eof())
{
// counts a line when an endline character is counted
if (character = '\n')
++lineNum;
charNum++;
inf.get(character);
if (character = EOF)
break;
}
inf.close();
inf.clear();
wordTabulate(inf, charNum, lineNum, length, fName);
}
void wordTabulate(ifstream& inf, int charNum, int lineNum, int count [], string fName)
{
inf.open(fName);
string word;
while (inf >> word)
{
cout << word;
count[word.size()]++;
}
inf.close();
inf.clear();
inf.open(fName);
output (inf, charNum, lineNum, count);
}
不幸的是,它只会计算 1 行、1 个字符,并且不会根据大小对单词进行分类。我为它编写的所有其他功能似乎都可以正常工作。我为字符计数器尝试了各种不同的方法,但似乎没有任何效果。您能提供的任何帮助将不胜感激。
下面我添加了输出功能。我确信有更好的方法从数组输出,但我现在并不太担心。
void output(ifstream& inf, int charNum, int lineNum, int count [])
{
int words = 0;
cout << "Characters: " << charNum << endl;
words = totalWord(count);
cout << "Words: " << words << endl;
cout << "Paragraphs: " << lineNum << endl;
cout << "Analysis of Words: " << endl;
cout << "Size 1 2 3 4 5 6 7 8 9 10+" << endl;
cout << "#Words" << count [2], count [3], count [4], count [5],
count [6], count [7], count [8], count [9], count [10];
}
这是我认为是罪魁祸首的打开文件功能。
bool fileOpen(string fileName, ifstream& inf, int wordTypes [])
{
int charNum = 0;
int lineNum = 0;
cout << "File? >" << endl; // asks for file name
cin >> fileName;
// opens file and indicates if file can be opened
bool Repeat ();
{
inf.open(fileName.c_str());
if (inf.is_open())
{
return true;
}
if (!inf.is_open())
{
return false;
}
}
}