首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >在哪里删除动态内存"char p"?

在哪里删除动态内存"char p"?
EN

Stack Overflow用户
提问于 2020-07-01 08:53:14
回答 1查看 82关注 0票数 1

这是一个绞刑游戏程序。我在中声明了char*p,但我不明白为什么我不需要在程序后面删除它。后来,我尝试删除它,但它给出了堆内存错误。另外,我是c++的新手--实际上我是编程新手--我也会感谢你能帮助我如何使这个程序的输出(在控制台上)看起来更有吸引力和交互性。比如我应该在哪里使用system("cls")命令,这样可以使它看起来更可读性更强,并删除不必要的信息。在程序的同一目录中创建一个名为easy、中等或hard的文件。这样当你运行程序时,它就可以从它那里得到输入。

代码语言:javascript
复制
#pragma once    
#include<iostream>
#include<string>
#include<ctime>
#include <cstdlib>
#include <stdlib.h>
#include <Windows.h>  
#include<fstream>
#include<ctime>
#include <chrono> // for measuring time
using namespace std;
using namespace chrono;

//scoring the game with recard to time....
// filing : user name unique id and all that
//storing the name of user , his score, long story short, make a record of every user who passes by
int len = 0, letterCount = 0, size = 0, guesses = 6;

class tstamp
{
    time_point<system_clock>tstart;
    time_point<system_clock>tstop;
public:
    void start()
    {
        tstart = system_clock::now();
    }
    void stop()
    {
        tstop = system_clock::now();
    }
    long long elasped()
    {
        return duration_cast<chrono::seconds>(tstop - tstart).count();
    }
};

int checkWin(string a, char *p)
{
    int count = 0;
    int i = 0;
    char *an = new char[a.length()];


    string word = p;

    for (i = 0; i < a.length(); i++)
    {
        if (a[i] == word[i])
            count++;

    }
    if (count == i)
        return 1; // 1 means the array is equal to the string  == win
    else
        return 0;  // not win
    delete[]an; // using delete here for 1st
}
void resetData(string nameOfPlayer)
{
    ofstream fout;
    fout.open(nameOfPlayer + ".txt", ios::trunc);
    //fout << "No Record";
    fout.close();


}



void playerDetails(string nameOfPlayer, string a, bool status, float timeTaken)
{
    char check = '\0';


    ofstream fout;
    fout.open(nameOfPlayer + ".txt", ios::app);
    if (status == true)
        fout << "Status : WON" << endl;
    else
        fout << "Status : LOST" << endl;
    fout << "Word : " << a << endl;
    fout << "Time taken to guess : " << timeTaken << " seconds" << endl;
    fout << "********************************************";
    fout << endl << endl;
    fout.close();
}

string * grow(string *p, string temp)  // to regrow the string array!!!!!
{
    string* newArray = new string[size + 1];
    for (int i = 0; i<size - 1; i++)
    {
        *(newArray + i) = *(p + i);

    }

    newArray[size - 1] = temp;
    delete[] p;
    return newArray;
}

char inGameMenu(char reset)
{
    reset = '\0';
    cout << "\n\t--->To reset your record press 'r' : ";
    cout << "\n\n\t--->To display your previous record press 'd' :  ";
    cout << "\n\n\t--->To continue press 'x' : ";
    cout << "\n\n\t--->To Exit the game press 'q' : ";
    cout << endl << "\n\n\t--->Your Choice : ";
    cin >> reset;
    return reset;


}

string provideWord(string *contents, string a)
{
    srand(time(NULL));
    int i = rand() % size;
    a = contents[i];
    return a;
}

string* read(string fileName, string contents[])
{
    string ext = ".txt";
    fileName = fileName + ext;
    fstream fin;
    fin.open(fileName);
    if (fin.is_open())
    {

        fin >> contents[0];
        size++;
        string temp;
        while (fin >> temp)
        {
            size++;
            contents = grow(contents, temp);
        }
    }
    else
        cout << "\n\tFile Not Found\n\n\n";
    return contents;
}

char * makeAsterisks(string temp)   // this will make astericks of the word player have to guess.
{
    int len = temp.length();
    char*p = new char[len];
    for (int i = 0; i < len; i++)
    {
        p[i] = '-';
    }
    p[len] = '\0';
    return p;
}

void displayRecord(string fileName, string display)
{
    fstream fout;
    fout.open(fileName + ".txt");
    cout << "\n----------------------------------------------------------------------------------------------------------------";
    if (fout.is_open())
    {
        cout << endl << endl;
        while (getline(fout, display))
            cout << display << endl;
    }
    else
        cout << "\n!!No Record Found!!\nYou might be a new user\n";
    cout << "\n----------------------------------------------------------------------------------------------------------------\n";
    fout.close();
}


char * checkMyGuess(string word, char userGuess, char ar[])
{
    bool flag = true;
    for (int i = 0; i < word.length(); i++)
    {
        if (userGuess == word[i])
        {
            flag = false;
            ar[i] = userGuess;
            letterCount++;
        }
    }
    if (flag == true)
    {
        _beep(450, 100);
        cout << "\n\t!!!Wrong!!!\n";
        len--;
        guesses--;
    }
    return ar;
}
void rules()
{
    system("Color 09 "); // for color effects

    cout << "\n\n\t\t\t=====================\n";
    cout << "\t\t\t||\tHANGMAN\t    ||\n\t\t\t||\tRules\t    ||"
        << "\n " << "\t\t\t=====================\n\n\n";
    _beep(4000, 500);

    system("Color 08 ");  // for color effects
    system("Color 07 "); // for color effects

    cout << "\t--> Computer will think of a word and you have try\n"   // rules
        << "\t to guess what it is one letter at a\n"
        << "\t time. Computer will draw a number of dashes \n "
        << "\tequivalent to the number of letters in the word.\n "
        << "\t If you suggest a letter that occurs\n "
        << "\t in the word, the computer will fill in the blank(s)\n"
        << "\t with that letter in the right place(s).\n"
        << "\t The session will be timed. \n\n";

    cout << endl;
    cout << "\t--> Total number of wrong choices : 6\n\n";  //wrong turns
    cout << "\t--> Objective : Guess the word / phrase before you run out of choices!\n\n";   // obj



}
int checkForName(string fileName)
{
    fileName = fileName + ".txt";
    char line = '\0';
    fstream fin;
    char fromFile[7] = "\t\tName";
    fin.open(fileName);

    int i = 0,
        check = 0;
    while (fin.get(line) && i < 7)
    {
        if (line == fromFile[i++])
            check++;
    }
    if (check == i - 1)
        return 1;
    else
        return 0;
    fin.close();

}
void checkForRecord(string fileName)
{
    fileName = fileName + ".txt";
    char line = '\0';
    fstream fin;
    char fromFile[7] = "No";
    fin.open(fileName);

    int i = 0,
        check = 0;
    while (fin.get(line) && i < 3)
    {
        if (line == fromFile[i++])
            check++;
    }
    if (check == i - 1)
    {
        fin.open(fileName, ios::trunc);
        fin.close();
    }

    fin.close();

}
int menu(int mode) // this function asks the user to enter the difficulty level of the game!!! You can't even beat medium!
{
    system("cls");
    cout << "Please select the Level of Game :\n";
    cout << "1. Easy" << endl;
    cout << "2. Medium" << endl;
    cout << "3. Hard" << endl << endl;
    cout << "Your Choice : ";
    cin >> mode;
    while (!(mode <= 3 && mode >= 1))
    {
        cout << endl << endl;
        cout << "Please Enter the number of given choices: ";
        cin >> mode;

    }
    return mode;
}
int comMenu(string nameOfPlayer, char reset)
{
    string readData;
    reset = '\0';
    while (1)
    {

        reset = inGameMenu(reset);
        if (reset == 'r')
        {
            resetData(nameOfPlayer);

            system("cls");
            Sleep(1);
        }
        else if (reset == 'd')
        {
            system("cls");
            Sleep(1);  // just to add a little delay!
            cout << "Your Record Shows :--->\n";
            displayRecord(nameOfPlayer, readData);
        }
        else if (reset == 'x')
            break;
        else if (reset == 'q')
            break;
        else
        {
            cout << "\n\n!!!Invalid Choice!!!\n\n";
        }
    }
    return reset;
}


int main()
{

    string nameOfPlayer;
    char anyKey = '\0';
    string name;
    cout << endl;

    rules();

    cout << "Enter the name of player: ";
    cin >> nameOfPlayer;



    while (1)
    {

        char reset = '\0';
        reset = comMenu(nameOfPlayer, reset);

        if (reset != 'q')  // check to exit the game
        {

            int uniquevar = checkForName(nameOfPlayer);
            if (uniquevar != 1)
            {
                ofstream fout;
                fout.open(nameOfPlayer + ".txt", ios::app);
                fout << "\t\tName of Player : " << nameOfPlayer << endl << endl << endl;   
                fout.close();
            }
            while (1)
            {
                system("Color E0");
                bool status = true; //initially win
                size = 0,
                    len = 0,
                    letterCount = 0,
                    guesses = 6;
                string a = ""; // it holds the word
                string *contents = new string[1];
                string name = "";
                char b;
                int mode = 0;
                tstamp ts;
                bool notRepeat[26] = { 0 };
                if (anyKey == 'X' || anyKey == 'x')
                    break;
                else
                {
                    mode = menu(mode);
                    if (mode == 1)
                        name = "easy";
                    else if (mode == 2)
                        name = "medium";
                    else if (mode == 3)
                        name = "hard";

                    contents = read(name, contents);
                    cout << endl;

                }
                a = provideWord(contents, a);
                delete[]contents;

                len = a.length();
                char *p = makeAsterisks(a);  // detele it later
                cout << "Total number of words to guesses: " << len << endl << endl;
                cout << "Total guesses you have: 6\n";
                cout << "Word :\n\n\t" << p << endl << endl;
                ts.start(); // it starts counting the time...
                while (guesses != 0)
                {
                    cout << "Enter char: ";
                    cin >> b;
                    if (b >= '1' && b <= '9')
                    {
                        cout << "\n\nThere is not number in the given word\n\n";
                        continue;
                    }
                    int temp = b - 97; //  it assigns the value of alphabet to temp i.e a=0,b=0 so on...

                    if (notRepeat[temp] != false)
                    {
                        cout << "\n\nYou've already used this word\n\n";
                        cout << "Remaining Choices: " << guesses << endl << endl;
                        continue;
                    }
                    else
                    {
                        p = checkMyGuess(a, b, p);
                        int checkingTheWin = checkWin(a, p);
                        if (checkingTheWin == 0)
                        {
                        }
                        else
                        {
                            cout << "\n\n\t*************You Won****************\n\n";
                            status = true; //true = win
                            break;
                        }
                        notRepeat[temp] = true;

                        cout << endl << endl;
                        cout << "Remaining Choices: " << guesses << endl;
                        cout << endl << '\t' << p << endl;
                    }
                }
                ts.stop();
                cout << "Time Taken: " << ts.elasped() << " seconds\n\n";
                p = NULL;
                if (guesses == 0)
                {
                    status = false; //false = lose
                    checkForRecord(nameOfPlayer);
                    playerDetails(nameOfPlayer, a, status, time); // right here it will create a file with the name of user
                    cout << "\n\nGame Over!!!\n\n";
                    cout << "\t\tThe word was \n\t\t\" " << a << "\"\n\n";
                }
                else
                {
                    checkForRecord(nameOfPlayer);
                    playerDetails(nameOfPlayer, a, status, time); // right here it will create a file with the name of user
                }
                
                break;

            }  //ending block of while(1) first
            system("color 07");  // shashka!!
        }

        if (reset == 'q') // to exit the game if the user decides so right away!!
            break;
    }
    
    cout << "Exiting the Game\n\n";
    _beep(3000, 500);  // ending sound!
    return 0;
}
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-07-01 09:07:57

makeAsterisks中,不允许使用空终止符。你需要再分配一个字符

代码语言:javascript
复制
char * makeAsterisks(string temp) 
{
    int len = temp.length();
    char*p = new char[len + 1]; // <-- change here
    for (int i = 0; i < len; i++)
    {
        p[i] = '-';
    }
    p[len] = '\0';
    return p;
}

话虽如此,您已经在使用string了,为什么不让自己的生活变得更轻松,并在任何地方使用它呢?下面是重写为使用makeAsterisksstring

代码语言:javascript
复制
string makeAsterisks(string temp) 
{
     return string(temp.length(), '-');
}
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/62673177

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档