【问题标题】:C++ open file.txt and take a random word (one word per line)C++ 打开 file.txt 并随机取一个单词(每行一个单词)
【发布时间】:2018-03-16 15:23:42
【问题描述】:

我从 c++ 开始,我只是在做一个小游戏,我想打开我的 file.txt,其中包含:

Hello
Test
Random
Mysterious
Nice
Good
Uber
Facebook
etc...

在我的代码中,我在变量中输入了一个词:

随机名称

那么我如何打开一个file.txt,在我的文件中随机取一个单词并插入到我的游戏中。我想我必须使用 ofstream 但我真的不知道如何使用它。

代码:

#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>

using namespace std;


string Shake(string str){

string melange;
int i(0);

while (str.size() != 0){

  i = rand() % str.size();
  melange += str[i];
  str.erase(i, 1);
 }

 return melange;
}

int main(){

std::cout << "Welcome to secret word : ";
string RandName("Random");
string Reponse("");
string RandNameShake("");
int cpt(0);
int lose(10);
int Replay(0);

srand(time(0));

std::cin >> Reponse;

while (RandName != Reponse && lose != 0) {
        RandNameShake = Shake(RandName);
        std::cout << "Wrong word ! " << '\n';
        std::cout << endl << "The secret word is : " << RandNameShake << endl;
        std::cout << "HIT : " << lose << '\n';
        std::cout << endl << "Try again : ";
        std::cin >> Reponse;
        cpt++;
        lose--;
}
if (lose == 0 ) {
    std::cout << endl << "Sorry you don't find the word ... " << '\n';
    std::cout << endl << "The word was : " << RandName <<'\n';
    std::cout << endl << "An other game ? 1/Yes 2/No" << '\n';

    std::cin >> Replay;
}
else
 std::cout << endl << "Good Game yu find the word in " << cpt << " hits" << endl;
 std::cout << endl << "An other game ? 1/Yes 2/No" << '\n';

 std::cin >> Replay;

if (Replay == 1) {
    main();
}
else if (Replay == 2) {
    std::cout << "All right see you soon :) !" << '\n';
    return 0;
}
else
     std::cout << "Don't understand i close the program" << '\n';
     return 0;

return 0;
}

【问题讨论】:

  • std::ofstream 用于输出(即类型名称中的第一个 'o' 的含义)。您需要std::ifstream - 如何使用它,您可以在网上或几乎任何 C++ 教科书中找到。
  • 这是我用来学习基本文件IO的:learncpp.com/cpp-tutorial/186-basic-file-io。你需要的课程是std::ifstream
  • 你可能会发现this的使用
  • 谢谢我会尝试
  • [teach-me] 因为这看起来很像家庭作业,请与您的教授/老师一起工作。这个问题表明,在你准备好编写代码之前,你需要更多的解释。

标签: c++ file text


【解决方案1】:

这听起来很像家庭作业,所以我将把代码留给你,并将答案限制在一般方向上。

我想我必须使用 ofstream

再试一次。 ofstream 顾名思义是用于输出的,在这种情况下你需要的是输入。

获取一个随机单词 - 一个低效的原生解决方案将涉及计算行/单词的数量,随机选择一个并向前跳过直到你到达它。然而,这涉及到许多可以避免的不必要的操作。

另一种效率低下的解决方案是将所有单词读入一个容器并从单词容器中随机挑选一个索引。但是,如果您要进行大量随机选词,那么该解决方案可能会更有效。

对于单个单词,最好在文件中随机选择一个位置并向前搜索,直到找到下一个新行,然后从该位置读取一行。如果你到达最后没有找到一个,这意味着该位置恰好在最后一行,所以你需要返回直到找到第一个新行,这将代表文件中的最后一行并读取它。

在任何一种情况下,您最终都会以最少的开销随机挑选一个单词。

【讨论】:

    猜你喜欢
    • 2021-05-26
    • 2012-11-09
    • 1970-01-01
    • 1970-01-01
    • 2013-10-07
    • 2018-04-05
    • 1970-01-01
    • 2012-05-20
    • 1970-01-01
    相关资源
    最近更新 更多