从.txt文件读取随机行 [英] Read random line from .txt file
问题描述
我正在尝试通过读取.txt文件中的随机单词来升级我的Hangman游戏.问题是,我不知道如何从.txt文件中读取随机行. .txt文件的每一行都包含一个单词.
I'm trying to upgrade my Hangman game by reading random words from a .txt file. Thing is, I can't figure out how to read a random line from the .txt file. There are single words on every new line of the .txt file.
void ler_palavras()
{
FILE *words;
if ((words = fopen("words.txt", "r")) == NULL) {
printf("Error! opening file");
exit(1);
}
// reads text until newline
fscanf(words,"%[^\n]", word);
fclose(words);
}
推荐答案
如果由于某种原因,您不能只将整个行集加载到内存中(太大或其他大小),则可以选择一种方法流条目集合中的随机条目.它不会无限扩展,并且会表现出较小的偏差,但这是一个游戏,而不是加密技术,因此不应该成为破坏交易的事情.
If, for some reason, you can't just load the whole set of lines into memory (too big or whatever), there is a way to select a random entry from a streaming set of entries. It won't scale indefinitely, and it will exhibit small biases, but this is a game, not cryptography, so that shouldn't be a dealbreaker.
逻辑是:
- 声明一个缓冲区来容纳单词
- 打开文件
- 对于每行:
- 增加一个计数器,指示您所在的行
- 生成随机的
double
(例如,使用drand48
或其他任何PRNG工具可供您使用) - 如果是
1.0 / lineno > randval
,请用当前行中的单词替换当前存储的单词(因此第一行是自动存储的,第二行替换的可能性为50%,第三行替换的可能性为33%,等)
- Declare a buffer to hold the word
- Open the file
- For each line:
- Increment a counter indicating which line you're on
- Generate a random
double
(e.g. withdrand48
or whatever PRNG facilities are available to you) - If
1.0 / lineno > randval
, replace the currently stored word with the word from the current line (so the first line is auto stored, the second line is 50% likely to replace it, the third is 33% likely to do so, etc.)
假设行数足够小(并且PRNG产生的double
的范围足够细),这将使选择给定行的可能性尽可能接近;两行,每行有50/50的命中率,三行是33.33 ...%,依此类推.
Assuming the number of lines is small enough (and the range of double
s produced by your PRNG is fine-grained enough), this gives as close as possible to an equal likelihood of any given line being selected; for two lines, each has a 50/50 shot, for three, 33.33...%, etc.
我现在缺少C编译器,但是基本代码如下:
I lack a C compiler right now, but the basic code would look like:
/* Returns a random line (w/o newline) from the file provided */
char* choose_random_word(const char *filename) {
FILE *f;
size_t lineno = 0;
size_t selectlen;
char selected[256]; /* Arbitrary, make it whatever size makes sense */
char current[256];
selected[0] = '\0'; /* Don't crash if file is empty */
f = fopen(filename, "r"); /* Add your own error checking */
while (fgets(current, sizeof(current), f)) {
if (drand48() < 1.0 / ++lineno) {
strcpy(selected, current);
}
}
fclose(f);
selectlen = strlen(selected);
if (selectlen > 0 && selected[selectlen-1] == '\n') {
selected[selectlen-1] = '\0';
}
return strdup(selected);
}
这篇关于从.txt文件读取随机行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!