1 Star 0 Fork 0

mobangjack / random_words

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
该仓库未声明开源许可证文件(LICENSE),使用请关注具体项目描述及其代码上游依赖。
克隆/下载
random_words.cpp 2.77 KB
一键复制 编辑 原始数据 按行查看 历史
mobangjack 提交于 2017-12-03 23:51 . init repo
#include <iostream>
#include <fstream>
#include <sstream>
#include <string>
#include <vector>
#include <ctime>
#include <cstdlib>
#include "random_words.h"
int load_count(const char *file)
{
int count = DEFAULT_NUMBER_OF_WORDS;
std::ifstream fcount(file);
if (!fcount)
{
std::cout << "[ERROR] can not open " << file << std::endl;
count = DEFAULT_NUMBER_OF_WORDS;
std::cout << "[WARNING] count was set to default: " << count << std::endl;
return count;
}
fcount >> count;
if (count < 1)
{
std::cout << "[ERROR] invalid count: " << count << std::endl;
count = DEFAULT_NUMBER_OF_WORDS;
std::cout << "[WARNING] count was set to default: " << count << std::endl;
fcount.close();
return count;
}
fcount.close();
return count;
}
std::string trim(std::string &str)
{
std::string s = str;
if (s.empty())
{
return s;
}
s.erase(0, s.find_first_not_of(" "));
s.erase(s.find_last_not_of(" ") + 1);
return s;
}
int load_words(const char *file, std::vector<std::string>& words)
{
std::ifstream fwords(file);
if (!fwords)
{
std::cout << "[ERROR] can not open " << file << std::endl;
return -1;
}
int total = 0;
std::string word = "";
while (std::getline(fwords, word))
{
word = trim(word);
if (word.empty()) continue;
words.push_back(word);
total++;
}
fwords.close();
return total;
}
std::string next_word(std::vector<std::string>& words)
{
std::string word = "";
if (words.empty())
{
return word;
}
size_t size = words.size();
int i = std::rand() % size;
word = words[i];
std::vector<std::string>::iterator it = words.begin() + i;
words.erase(it);
return word;
}
void info(int count, int total)
{
std::cout << "☆☆☆☆☆ 随机取词工具 ☆☆☆☆☆" << std::endl;
std::cout << "词典总条目数:" << total << std::endl;
std::cout << "随机抽取词数:" << count << std::endl;
std::cout << "按回车键开始取词" << std::endl;
}
int run()
{
int count = load_count(DEFAULT_COUNT_FILE_NAME);
std::vector<std::string> words;
int total = load_words(DEFAULT_WORDS_FILE_NAME, words);
if (total < 1)
{
std::cout << "[ERROR] can not load words, total: " << total << std::endl;
return -1;
}
info(count, total);
getchar();
srand((unsigned)clock());
std::string word = "";
for (int i = 0; i < count; i++)
{
// getchar();
word = next_word(words);
std::cout << i + 1 << ". " << word << std::endl;
}
return 0;
}
int main(int argc, char *argv[])
{
int ret = 0;
int key = 0;
while (ret == 0)
{
ret = run();
if (ret != 0)
{
std::cout << "程序加载异常,请按回车键退出" << std::endl;
key = getchar();
break;
}
std::cout << std::endl << "√完成取词,按Q键回车退出,直接回车重新加载" << std::endl;
key = getchar();
if (key == 'q' || key == 'Q') break;
}
return ret;
}
1
https://gitee.com/mobangjack/random_words.git
git@gitee.com:mobangjack/random_words.git
mobangjack
random_words
random_words
master

搜索帮助