【发布时间】: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]因为这看起来很像家庭作业,请与您的教授/老师一起工作。这个问题表明,在你准备好编写代码之前,你需要更多的解释。