MFC中生成随机数

1 篇文章 0 订阅

使用MFC生成随机数

创建界面

随机数生成界面
两个编辑框,一个用于保存生成的随机数文件,另一个用于定义生成数据量的大小,这里生成的数据是十六进制保存的。

生成数据并保存

在xxxdlg.cpp中需要include time.h

void RdmToolsDlg::OnBnClickedButtonRandom()
{
	// TODO: 在此添加控件通知处理程序代码
	UINT m_u32Size;
	CString m_csSize;
	UpdateData(true);
	GetDlgItem(IDC_EDIT_SIZE)->GetWindowText(m_csSize);
	if (m_csSize == _T("0") || m_csSize.IsEmpty())
	{
		AfxMessageBox("Please enter a right number!");
	}
	m_u32Size = _ttoi(m_csSize);

	CString filepath;
	GetDlgItem(IDC_EDIT_PATH)->GetWindowText(filepath);

	CFile File;
	CFileException e;
	if (!File.Open(filepath, CFile::modeCreate | CFile::modeReadWrite, &e)) //会创建一个新的文件
	{
		CString strErr;
		strErr.Format(_T("File could not be opened %d\n"), e.m_cause);
		MessageBox(strErr);
	}

	CString strres, strtmp;
	srand((unsigned)time(NULL));
	for (int i = 0; i < m_u32Size; i++)
	{
		strtmp.Format(_T("%.2x"), rand() % 256);
		strres += strtmp;
		if ((i+1) % 4 == 0) //以32位格式保存在文件中
		{
			strres += "\r\n";
		}	
	}
	File.Write(strres, strlen(strres));
	File.Close();
	AfxMessageBox("File generated.");

}

测试的时候发现了一个问题,每次生成的数都是一样的,问题出在==strtmp.Format(_T(“%.2x”), rand() % 256);==这里,这里不能使用_T(),否则每次保存下来的值都会是一样的,直接去掉就可以。

strtmp.Format("%.1x", rand() % 16);

修正后代码

void RdmToolsDlg::OnBnClickedButtonRandom()
{
	// TODO: 在此添加控件通知处理程序代码
	UINT m_u32Size;
	CString m_csSize;
	UpdateData(true);
	GetDlgItem(IDC_EDIT_SIZE)->GetWindowText(m_csSize);
	if (m_csSize == _T("0") || m_csSize.IsEmpty())
	{
		AfxMessageBox("Please enter a right number!");
	}
	m_u32Size = _ttoi(m_csSize);

	CString filepath;
	GetDlgItem(IDC_EDIT_PATH)->GetWindowText(filepath);

	CFile File;
	CFileException e;
	if (!File.Open(filepath, CFile::modeCreate | CFile::modeReadWrite, &e)) //会创建一个新的文件
	{
		CString strErr;
		strErr.Format(_T("File could not be opened %d\n"), e.m_cause);
		MessageBox(strErr);
	}

	CString strres, strtmp;
	srand((unsigned)time(NULL));
	for (int i = 0; i < m_u32Size; i++)
	{
		strtmp.Format("%.2x", rand() % 256);
		strres += strtmp;
		if ((i+1) % 4 == 0) //以32位格式保存在文件中
		{
			strres += "\r\n";
		}	
	}
	File.Write(strres, strlen(strres));
	File.Close();
	AfxMessageBox("File generated.");

}

随机数生成结果

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值