WordCount-第二次作业

gitee:https://gitee.com/coNgY1/word-count/

1.功能分析

  WordCount的需求可以概括为:对程序设计语言源文件统计字符数、单词数、行数,统计结果以指定格式输出到默认文件中,以及其他扩展功能,并能够快速地处理多个文件。可执行程序命名为:wc.exe,该程序处理用户需求的模式为:

wc.exe [parameter] [input_file_name]

2.思路
C++来写,一个CFileRecord类来统计。

3.代码:

#include<iostream>
#include<fstream>
#include<string>
#include<sstream>
#include<algorithm>
#include<vector>
using namespace std;

class CFileRecord
{
private:
	int m_Wordnum;
	int m_Charnum;
	int m_Linenum;
	string m_record;
	const string OUT_FILE = "result.txt";
	ifstream input;
	ofstream out;

public:
	vector<string> m_mode;

public:
	CFileRecord(string szFile) :m_Wordnum(0), m_Charnum(0), m_Linenum(0), input(szFile), out(OUT_FILE){ 
		if (input.is_open() && out.is_open())
		{
			string szLine;
			while (getline(input, szLine))
			{
				m_Linenum++;
				m_Charnum += szLine.size();
				istringstream record(szLine);
				string word;
				while (record >> word)
				{
					m_Wordnum += count(begin(word), end(word), ',') + 1;
				}
			}
		}
		m_record = "字符数 : " + to_string(m_Charnum) + "\r\n"
						+"单词数 : " + to_string(m_Wordnum) + "\r\n"
						+"行数 : " + to_string(m_Linenum) + "\r\n";
		out << m_record;
	}
	~CFileRecord()
	{
		if(input.is_open())
			input.close();
		if(out.is_open())
			out.close();
	};
	int GetCharnum() { return m_Charnum; }
	int GetLinenum() { return m_Linenum; }
	int GetWordnum() { return m_Wordnum; }
	void OutRecord(string szFile)
	{
		ofstream out(szFile,ostream::ate);
		if (out.is_open())
		{
			for (auto iter = m_mode.begin(); iter != m_mode.end(); iter++)
			{
				if (*iter == "-c")
					out << "字符数 : " + to_string(m_Charnum) + "\r\n";
				else if (*iter == "-l")
					out << "行数 : " + to_string(m_Linenum) + "\r\n";
				else if (*iter == "-w")
					out << "单词数 : " + to_string(m_Wordnum) + "\r\n";
			}
			out.close();
		}
	}

};


int main(int argc,char **argv)
{
	string szInfile;
	string mode;
		
	if (argc % 2 == 0)
	{
		//cout << "wrong param!" << endl;;
		return 1;
	}

	szInfile = argv[2];
	CFileRecord CRecord(szInfile);

	for (int i = 1; i < argc; i += 2)
	{
		mode = argv[i];
		szInfile = argv[i+1];
		CRecord.m_mode.push_back(mode);
		if (mode == "-c")
			cout << szInfile << ",字符数: " << CRecord.GetCharnum() << endl;
		else if (mode == "-l")
			cout << szInfile << ",行数: " << CRecord.GetLinenum() << endl;
		else if (mode == "-w")
			cout << szInfile << ",单词数: " << CRecord.GetWordnum() << endl;
		else if (mode == "-o")
			CRecord.OutRecord(szInfile);
	}

	return 0;
}

  

四.测试

 

转载于:https://www.cnblogs.com/coNgY1/p/9696626.html

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值