【发布时间】:2013-09-06 22:50:25
【问题描述】:
我正在尝试使用以下函数计算文件中的字符数和行数。
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;
}
}
}
【问题讨论】:
-
问题在这里:
if (character = '\n')和这里if (character = EOF),你的意思是if (character == '\n')和if (character == EOF) -
这使它不能只计算一个字符和一行,但现在它永远不会输出并且似乎卡在 while 循环中。
-
你检查过 unix util 'wc -m/w/l' 以供参考吗?
-
现在卡在了两个 while 循环中的哪一个?您应该在这里投入大部分精力。
-
为什么在调用 wordTabulate 之前关闭流,它试图从流中读取?这似乎可能是错误的,但我不确定。 “输出”的源代码在哪里?
标签: c++