首页 > 解决方案 > 为游戏读写文件

问题描述

我正在使用随机初始化的字母(例如 BASTEN)制作游戏,用户将仅使用这些字母键入尽可能多的单词。我有一个文件,其中包含正确的单词及其对应点。我的问题是如何防止用户一遍又一遍地使用相同的单词?

我正在尝试使用 ofstream 以便每当用户输入正确的单词时,它将被添加到空白文件中

void start()
{
    char ch;
    do {
        clrscr();
        long* newptr = 0;
        time_t start = time(newptr);
        char arr[10][50] = {" B A N S E T ", " R E D G A E ", " S A H L E S ", " P R G N I S ",
                            " A L E R L Y ", " L A C S A U ", " A C Q U K Y ", " M B L U E J ",
                            " Z E D Z U B ", " L E A Z D Z "};
        int i = 0, sum, x;
        while (i != 2) {
            clrscr();
            sum = 0;
            do {
                clrscr();
                cout << "\t**********************************************\n";
                cout << "\t*             W O R D  S E E K E R           *\n";
                cout << "\t**********************************************\n";
                cout << "\n\t\t\t\t\t SCORE: " << sum << " /50 pts"
                     << "\n                  ******************************\n";
                cout << "                  *       " << arr[i] << "        *\n";
                cout << "                  ******************************\n\n";
                cout << " 6 letter=10pts, 5 letter=8pts, 4 letters=6pts, 3 letter=4pts\n\n";
                char a[20], b[20];
                int c;

                // this is where I have my problem
                if (i == 0) {
                    ifstream fin;
                    fin.open("lvl1.txt");
                    if (fin.fail()) {
                        cout << "File doesn't exist!";
                        exit(1);
                    }
                    ofstream fout;
                    fout.open("trial.txt");
                    if (fout.fail()) {
                        cout << "Output file opening failed.\n";
                    }
                    cout << "\tEnter word: ";
                    cin >> a;

                    do {
                        fout << a;
                        fin >> b >> c;
                        if (fin.eof() == 1) {
                            cout << "Incorrect! Try Again!";
                            delay(1000);
                            exit(1);
                        }
                    } while (strcmp(a, b) != 0);
                    fin.close();
                    if (strcmp(a, b) == 0) {
                        sum += c;
                    }
                }
            } while (sum < 50);
            i++;
        }
        x = time(newptr) - start;
        cout << "\n\tGood Job! Your time is " << x << " seconds\n";
        cout << "\tDo you want to continue?(Y/N): ";
        cin >> ch;
    } while (ch != 'n' || ch != 'N');
}

标签: c++fstreamifstreamofstreamturbo-c++

解决方案


一个问题是您是否想在运行时或程序结束后记住这些单词。

要在程序结束后记住单词,请将它们写入文件。

要记住用户在运行时输入的单词,请使用容器,例如std::vector. 将单词附加到容器中,然后对容器进行排序。在追加之前,您可以使用std::binary_search在容器中查找单词。


推荐阅读