我如何有效地清理此程序并仍然检测文件输入何时不是字母
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 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 是字符数组。
相关文章:
- 检测 COFF 对象文件中C++内联符号
- 在C++中使用 freopen 时如何检测文件结尾?
- 编译的C可执行文件被Windows defender检测为病毒
- 如何检测将文本文件读入 int 数组的新行
- C++ 生成文件未检测到 .h 文件中的更改
- "configure"脚本如何检测我的系统是否支持某些头文件或 cpp 功能?
- 如何检测文件夹是否太重,如果是,请删除其中的一部分
- 检测到 Conan 配置文件设置与 CMake 之间的编译器版本不匹配
- 通过终端在文件中输入时检测EOF(文件结束)时出现问题
- 读取文件时检测到堆栈粉碎
- 如何检测两个文件条目是否引用与Qt相同的物理文件系统?
- 如何检测哪些进程更改,重命名或创建文件?
- 如何让Visual Studio自动检测子文件夹中的.cpp文件?
- 仅捕获异常就可以检测所有二进制文件在C 中读取错误是否足够
- 递归功能轨道目录未检测到所有文件夹
- 在 c++ 中动态检测文件的字符集
- 观看文件夹和子文件夹以进行文件更改,这不是检测更改
- 使用不带无限循环的 C++ i 检测文本文件中的更改
- C++ boost::文件系统如何检测路径是文件还是目录
- 生成文件自动 SRC 文件检测和依赖项生成