代码实现
WordStatistic.h:
#pragma once
#include <iostream>
#include "string.h"
using namespace std;
#define OUT 0 //单词外
#define IN 1 //单词内
#define INIT OUT //初始状态为单词外
class WordStatistic
{
public:
//初态 字符外为0 字符内为1
int status;
//统计文本字数
void word_amount();
//判断字符是否是标点符号
bool is_symbol(char &c);
};
WordStatistic.cpp:
#include "WordStatistic.h"
#include "fstream"
//字符统计
void WordStatistic::word_amount(){
//定义文件流对象
fstream ifs;
//当前状态
int status = INIT;
//读取指定文件内的字符
ifs.open("test.txt",ios::in);
if (!ifs.is_open())
{
cout<<"文件打开失败"<<endl;
}
else
{
cout<<"文件打开成功"<<endl;
//定义变量amount初始值为0用来记录指定文件内的字符数量
int amount = 0;
//挨个读取字符并调用函数判断字符是否是标点符号 如果不是标点符号,字符变量++
char c;
while( (c = ifs.get()) != EOF)
{
// cout<<c<<endl;
//遇到字符 - 状态不变
if (c == '-')
{
//符号-后面紧跟换行符的话状态不变
if((c = ifs.get()) == '\n');
continue;
}
if (is_symbol(c))
{
status = OUT;
}
else if(status == OUT)
{
status = IN;
amount++;
}
}
ifs.close();
cout<<"本篇文章的总字数为: "<<amount<<endl;
}
}
//判断是否是标点
bool WordStatistic::is_symbol(char &c){
if (c == ',' || c == '.' || c == '/' || c == '?' || c == ';' || c == '+' || c == ' ' || c == '\n')
{
return 1;
}
else
return 0;
}
main.cpp
#include <iostream>
#include <fstream>
#include "WordStatistic.h"
using namespace std;
int main()
{
WordStatistic file;
file.word_amount();
// cout<<"hello world"<<endl;
return 0;
}
测试文本test.txt
sdf asdfsdf asdfsdf asdf jlkj, , . / sdf-
sdf soij-sadfh -
sdfs
kkkk