簡體   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