我如何有效地清理此程序并仍然检测文件输入何时不是字母

How can I clean this program efficiently and still detect when the file input is not a letter?

本文关键字:文件 检测 输入 何时不 有效地 程序      更新时间:2023-10-16

这是我的整个程序,我应该从一个名为hw4pr11input.txt的输入文件中计算单词中的平均字母数。我只编程了几个星期,所以我会感谢我可以用我的少量知识实现的简单答案。我还不知道数组是什么,我正在做功课的章节在文件io上。

#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 Openn";
         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文件选择了此符号列表。我删除了评论,因为它们使复制和粘贴变得困难,如果这使我的逻辑更难以理解,我深表歉意。

感谢您的帮助。:)放轻松。

您可以使用

转换为无符号整数的字符std::bitset<255>,并仅将那些作为单词字符的字符预设为 true。 在你的循环中,你只需查找它是否是一个有效的单词。

请注意,这假设 char 是 255 位而不是 unicode。 您可以相应地调整位集的大小。

这使您可以非常快速地检查字符是否为单词字符,并允许您定义要包含的字符(例如,如果要求突然更改为包含"-"。

您可以通过

将这些字符组存储在字符串中来美化此代码。然后你可以编写一个函数,它接受一个 char 和一个字符串,并检查 char 是否等于给定字符串中的任何 char。但这需要你学习如何使用数组,因为字符串 i C 是字符数组。