这是我的整个程序,我应该从名为 hw4pr11input.txt 的输入文件中计算单词中的平均字母数。我只编程了几个星期,所以我很感激简单的答案,我可以用我的少量知识来实现。我还不知道数组是什么,我正在做作业的那一章在文件 io.xml 中。
#include <fstream>
#include <iostream>
#include <cstdlib>
using namespace std;
//function declaration
void average_letters(ifstream& fin);
//Precondition: there is a input file with text ready to be read
//postcondition: Text from the input file is read then the average length of
//words is calculated and output to the screen
//start main program
int main()
{
ifstream fin;
fin.open("hw4pr11input.txt"); //opening input file
if (fin.fail()) //checking for input file opening failure
{
cout << "Input file open fail";
exit(1); //terminating program if check fails
}
cout << "File Open\n";
average_letters(fin); //calling function to remove spaces
system("pause");
return 0;
}
//function definition, uses iostream and fstream
void average_letters(ifstream& fin)
{
char next, last_char = 0;
double letter_count = 0, word_count = 0;
double average = 0;
while(!(fin.eof()))
{
fin.get(next);
if(!(next == ' ' || next == ',' || next == '.' || next == '/'
|| next =='(' || next == ')'))
{
letter_count++;
}
else
{
if((next == ' ' || next == ',' || next == '.' || next == '/'
|| next =='(' || next == ')') && (last_char == ' ' || next == ','
|| next == '.' || next == '/' || next =='(' || next == ')' ))
{
continue;
}
else
{
word_count++;
}
}
last_char = next; //stores previous value of loop for comparison
}
average = letter_count/word_count;
cout << "The average length of the words in the file is:" << " " <<average;
cout << endl;
}
我相信这个程序可以完成任务,但我主要关心的是函数 average_letters 的一部分,它检查它是字母还是符号。我通过查看 .txt 文件选择了这个符号列表。我删除了评论,因为它们使复制和粘贴变得困难,如果这使我的逻辑更难以理解,我深表歉意。
谢谢你的帮助。对我放轻松:)。