gihub:https://github.com/3118004952/wc.exe
一、题目描述
1、Word Count
1. 实现一个简单而完整的软件工具(源程序特征统计程序)。
2. 进行单元测试、回归测试、效能测试,在实现上述程序的过程中使用相关的工具。
3. 进行个人软件过程(PSP)的实践,逐步记录自己在每个软件工程环节花费的时间。
2、WC 项目要求
wc.exe 是一个常见的工具,它能统计文本文件的字符数、单词数和行数。这个项目要求写一个命令行程序,模仿已有wc.exe 的功能,并加以扩充,给出某程序设计语言源文件的字符数、
单词数和行数。实现一个统计程序,它能正确统计程序文件中的字符数、单词数、行数,以及还具备其他扩展功能,并能够快速地处理多个文件。
具体功能要求:
程序处理用户需求的模式为:
wc.exe [parameter] [file_name]
基本功能列表:
wc.exe -c file.c //返回文件 file.c 的字符数
wc.exe -w file.c //返回文件 file.c 的词的数目
wc.exe -l file.c //返回文件 file.c 的行数
扩展功能
支持 -s 参数
支持 -a 参数
支持各种文件的通配符(*,?)
高级功能
基本的Windows GUI 程序操作
支持通过图形界面选取文件
支持通过图形界面展现文件的信息
二、解题思路
检测用户输入指令,再根据指令执行相应操作
统计字符操作:一行一行读取字符,统计每行的字符数
统计词操作:一行一行读取字符,统计每行的词数
统计行数操作:使用getline函数依次读取每一行,直到结尾,记录行数
三、关键代码
主函数:读取指令与判别指令
1 #include2 #include "wc.h" 3 4 int main() 5 { 6 int num; 7 char getcommand[256];//保存命令 8 while (1) 9 { 10 std::cout << "wc.exe "; 11 std::cin.getline(getcommand, 256); 12 num = 0; 13 while (num < 256 && getcommand[num] != '\0') 14 { 15 if (getcommand[num] == '-')//取得命令的开头 16 { 17 if (getcommand[num + 1] == 'r') //退出程序 18 return 0; 19 if (getcommand[num + 1] == 'c' || getcommand[num + 1] == 'w' || getcommand[num + 1] == 'l') {}//判断指令是否正确 20 else 21 { 22 std::cout << "指令不存在!\n"; 23 break; 24 } 25 int i = num + 2; 26 int j = 0; 27 char save[256]; 28 std::ifstream fr; 29 while (getcommand[i] == ' ')//判断指令格式是否正确 30 { 31 i++; 32 } 33 if (i == num + 2)//说明指令后面没有跟空格 34 { 35 std::cout << "输入错误!\n"; 36 break; 37 } 38 while (getcommand[i] != '\0')//取文件路径或名字 39 { 40 save[j++] = getcommand[i++]; 41 } 42 save[j] = '\0'; 43 fr.open(save, std::ifstream::in);//打开文件 44 if (!fr.is_open()) 45 { 46 std::cout << "文件不存在!\n"; 47 break; 48 } 49 switch (getcommand[++num]) 50 { 51 case 'c': 52 std::cout << "字符数:"<< characters(&fr)<<"\n"; 53 break; 54 case 'w': 55 std::cout << "词数:" << words(&fr) << "\n"; 56 break; 57 case 'l': 58 std::cout << "行数:" << lines(&fr) << "\n"; 59 break; 60 default: 61 break; 62 } 63 } 64 else 65 { 66 if (getcommand[num] != ' ')//判断命令格式是否正确 67 break; 68 } 69 num++; 70 } 71 } 72 }
统计字符数函数
1 int characters(std::ifstream *fr) 2 { 3 int m = 0, n = 0; 4 char str[256]; 5 while (fr->getline(str, 256)) 6 { 7 n = 0; 8 while (str[n++] != '\0') 9 { 10 m++; 11 } 12 } 13 return m; 14 }
统计词数函数
int words(std::ifstream *fr) { int m = 0, n = 0, j = 0; char str[256]; while (fr->getline(str, 256)) { n = 0; while (str[n] != '\0') { if ((str[n] >= 'a' && str[n] <= 'z') || (str[n] >= 'A' && str[n] <= 'Z') || (str[n] >= '0' && str[n] <= '9')) { j = 1; } else { if (j == 1) { m++; j = 0; } } n++; } if (j == 1) m++; j = 0; } return m; }
统计行数函数
1 int characters(std::ifstream *fr) 2 { 3 int m = 0, n = 0; 4 char str[256]; 5 while (fr->getline(str, 256)) 6 { 7 n = 0; 8 while (str[n++] != '\0') 9 { 10 m++; 11 } 12 } 13 return m; 14 }
四、项目测试