读取和写入游戏文件

时间:2019-04-19 13:46:47

标签: c++ fstream ifstream ofstream turbo-c++

我正在用随机初始化的字母(例如B A S T E N)制作游戏,并且用户将仅使用这些字母键入尽可能多的单词。我有一个文件,其中包含正确的单词及其对应的要点。我的问题是如何防止用户反复使用相同的单词?

我正在尝试使用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');
}

1 个答案:

答案 0 :(得分:0)

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

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

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