【问题标题】:How can I get this array to populate with my Input Values?如何让这个数组填充我的输入值?
【发布时间】:2012-04-19 17:26:22
【问题描述】:

我正在尝试填充一个我希望是“动态”的数组,以便我可以在运行时根据需要向其中输入尽可能多的条目。但是,我认为指针 NthTeam 指向的数组没有填充:

int* NthTeam = NULL;    

NthTeam = (int*)realloc(NthTeam,(playerCounter*STND_NO_GAMES)*sizeof(int));

// loops through each player's standard number of games
for (int i = 1; i <= STND_NO_GAMES; i++) {
    //input the score into the remalloced array
    cout << "Enter player " << playerCounter << "'s score " << i << ": ";
    cin >> inputValue;
    NthTeam[((playerCounter-1)*STND_NO_GAMES+(i-1)))] = SanityCheck(inputValue);
 }

但是,当我在我的代码中使用 cin &gt;&gt; NthTeam[(playerCounter - 1) * STND_NO_GAMES + (i - 1)] 时,它确实有效...填充了数组。

this link 让我相信您可以像使用常规数组一样使用 NthTeam,但我不认为这就是这里发生的事情。我不能只使用cin 的原因是因为我应该在允许输入进入数组之前对输入执行有效性检查。

我在谷歌上搜索答案很迷茫;对于我现在所处的位置来说,其中大部分都太复杂了。

【问题讨论】:

  • 嗨,您将问题标记为 c,但代码看起来像 c++。请说清楚是哪一个。
  • 你为什么使用 realloc 而不是 malloc?
  • 您不应该使用realloc 来重新分配内存以更改大小。您应该使用malloccalloc
  • 这是在do...while循环的中间,我摘录了代码。 playerCounter 不断迭代。
  • 当然,在 C++ 中,您根本不应该使用 mallocrealloc 等。我真诚地希望你的班级没有教你。你最好使用标准容器,例如vector

标签: c++ arrays pointers


【解决方案1】:

假设您使用 C++ 编程,标准库可以提供帮助。例如:std::vector。这里是脑残修改,一定要#include &lt;vector&gt;

std::vector<int> NthTeam;    

// loop through each player's standard number of games
// inputting the score into the vector

for (int i = 1; i <= STND_NO_GAMES; i++) {
    cout << "Enter player " << playerCounter << "'s score " << i << ": ";
    cin >> inputValue;
    NthTeam.push_back(SanityCheck(inputValue));
}

您确实需要考虑输入无效输入时会发生什么(例如输入“番茄”的分数)。考虑这将如何影响cin 的错误状态,如果您在最后一次尝试产生错误时尝试从中读取另一个整数会做什么,以及inputValue 会是什么。

您可能仍然需要“SanityCheck”...但它可能会理所当然地认为它只需要检查整数。

【讨论】:

    猜你喜欢
    • 2018-05-22
    • 1970-01-01
    • 2023-03-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-02-10
    相关资源
    最近更新 更多