[英]How can I clean this program efficiently and still detect when the file input is not a letter?
這是我的整個程序,應該從一個名為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 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文件選擇了此符號列表。 我刪除了評論,因為它們使復制和粘貼變得困難,如果這會使我的邏輯更難以理解,我深表歉意。
謝謝你的幫助。 放輕松我:)。
您可以使用std::bitset<255>
來使用轉換為無符號整數的字符,並僅將那些為單詞字符的字符預置為true。 在循環中,您只需查找其是否為有效單詞。
請注意,這以char為255位而不是unicode為前提。 您可以相應地放大您的位集。
這使您可以非常快速地檢查字符是否為文字字符,並可以定義要包含的字符(例如,如果要求突然變為包含“-”的情況)。
您可以通過將這些字符組存儲在字符串中來美化此代碼。 然后,您可以編寫一個函數,該函數接受一個char和一個字符串,並檢查char是否等於給定字符串中的任何char。 但這需要您學習如何使用數組,因為字符串i C是char數組。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.