Created
July 24, 2012 05:36
-
-
Save autophyte/3168239 to your computer and use it in GitHub Desktop.
跟据文件中的词随机创建名字
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//random_name.cpp | |
#include <iostream> | |
#include <cstdlib> | |
#include <ctime> | |
#include <vector> | |
#include <set> | |
#include <string> | |
#include <fstream> | |
#include <stdio.h> | |
using namespace std; | |
const int MAXNAMECOUNT = 3; //定义最多只能够使用3个词构成名字 | |
int read_file(vector<wstring> &des, const wchar_t *p_file_name) | |
{ | |
FILE *fp = _wfopen(p_file_name, L"r"); | |
if(fp==NULL) return 0; | |
wchar_t *p, *e; | |
wchar_t buf[50]=L""; | |
while(p = fgetws(buf, 50, fp)) | |
{ | |
e = wcsstr(buf, L"\n"); | |
if (NULL!=e) *e=L'\0'; | |
e = wcsstr(buf, L"\r"); | |
if (NULL!=e) *e=L'\0'; | |
des.push_back(buf); | |
wmemset(buf, L'\0', 50); | |
} | |
fclose(fp); | |
} | |
int r(unsigned int range) | |
{ | |
srand((unsigned)time(NULL)); //用于保证是随机数 | |
return range>0?(rand()%range):0; //用rand产生随机数并设定范围 | |
} | |
int main(int argc, char *argv[]) | |
{ | |
if (argc<2) return -1; //确认命令行输入参数中包含需要生成的名字的数量 | |
vector<wstring> ln, fn; | |
int i_ln_count = read_file(ln, L"f:\\ln.txt"); //从文件中读取姓 | |
if (0== i_ln_count) return -1; | |
cout << "test" << endl; | |
int i_fn_count = read_file(fn, L"f:\\fn.txt"); //从文件中读取名 | |
if (0== i_fn_count) return -1; | |
int i_count = atoi(argv[1]); //第二个参数为生成名字的数量 | |
set<wstring> name_set; | |
wstring str_name; | |
for (int i=0; i<i_count; ++i) | |
{ | |
int i_index_ln = r(i_ln_count); //生成姓的编号 | |
str_name = ln[i_index_ln]; | |
int i_count_fn = r(MAXNAMECOUNT)+1; | |
for (int j=0; j<i_count_fn; ++j) | |
{ | |
int i_index_fn = r(i_fn_count); //生成名字的词的编号 | |
str_name+=fn[i_index_fn]; | |
} | |
name_set.insert(str_name); | |
str_name=L""; | |
} | |
for (set<wstring>::iterator itr=name_set.begin(); itr!=name_set.end(); ++itr) | |
wcout << *itr << endl; | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment