繁体   English   中英

动态数组,接受用户输入来确定大小

[英]Dynamic Array, Accepting User Input to Determine Size

因此,我们正在开展一个项目,我们在其中写入文件以跟踪纸牌游戏得分。 在程序开始时,应询问用户将有多少玩家,然后输入他们的名字。 根据我对 C++ 的了解,我认为保存名称的数组是最好的。 我对其他建议持开放态度,但这就是我所拥有的。 当我尝试运行程序时,它会询问他们的姓名,然后抛出异常“写访问冲突”。 我能想到的最好的办法是我使用了 auto 和指针错误,但我不确定如何修复它。

#include <iostream>
#include <string>

using namespace std;

int getPlayerNum() {
    cout << "How many people are playing?";
    int length{};
    cin >> length;

    return length;
}

int getRounds(int number) {
    cout << "How many rounds will you play?";
    int number;
    cin >> number;

    return number;
}

void getPlayerName(string* names, int length) {
    for (int i=1; i<= length; i++) {
        cout << "Hello player " << i << ", What should I call you?";
        cin << names[i];
    }
}

int main ()
{
    fstream gameFile;
    int x, i, gameRound, playerScore;
    int numPlayers{getPlayerNum()};

    cout << "Welcome, I'll keep score while you play!";

    getRounds(gameRound);

    auto* playerNames{new string[numPlayers]{}}; //array to hold the names
    getPlayerNames(playerNames, numPlayers); 


    gameFile.open("gameScore.txt", ios::out);

    if (gameFile.is_open) {
        for (x = 1; x <= gameRound; x++) {
            gameFile << "\n==== Round #" << x << " ====" << endl;

            for (i=1; i <= numPlayers; i++) {
                cout << "Hello " << playerNames[i] << " , What was your score this round?";
                cin >> playerScore;

                gameFile << playerNames[i] << ": " << playerScore << endl;
            }
        }
        gameFile.close()
    }


}

我建议您使用动态 memory。

而不是将您的数组声明为:

auto* playerNames{new string[numPlayers]{}}

利用:

string* playerNames = new String[numPlayers]

然后像往常一样使用数组示例: cout << playerNames[1];

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM