[英]How can I get this array to populate with my Input Values?
I'm trying to populate an array that I'm hoping is "dynamic", so that I can input as many entries into it as I need at runtime. 我试图填充一个我希望是“动态”的数组,以便在运行时可以根据需要在其中输入尽可能多的条目。 However, the array, to which I presume the pointer
NthTeam
is pointing to, is not populating: 但是,我假设指针
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);
}
However, when I use cin >> NthTeam[(playerCounter - 1) * STND_NO_GAMES + (i - 1)]
in my code, it does work...the array populates. 但是,当我在代码中使用
cin >> NthTeam[(playerCounter - 1) * STND_NO_GAMES + (i - 1)]
时,它确实起作用了……该数组已填充。
I was led to believe from this link that you could use NthTeam just as you would a regular array, but I don't think that's what's happening here. 我被认为从此链接可以使用NthTeam就像使用常规数组一样,但是我认为这不是正在发生的事情。 The reason I can't just use
cin
is because I'm supposed to be performing a validity check on the input before allowing it into the array. 我不能只使用
cin
的原因是因为我应该在允许输入进入数组之前对输入执行有效性检查。
I'm very lost Googling for answers; 我迷失了谷歌搜索的答案; much of it is too complex for where I am now.
对于我现在的位置来说,很多事情太复杂了。
Assuming you are programming in C++, the standard library is there to help. 假设您使用C ++进行编程,则可以使用标准库。 For instance: std::vector .
例如: std :: vector 。 Here's a brain-dead modification, and be sure to
#include <vector>
: 这是一个脑筋急转弯的修改,请确保
#include <vector>
:
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));
}
You do need to think about what will happen when invalid input is entered (like entering a score of "tomato"). 您确实需要考虑输入无效输入(例如输入分数“番茄”)时会发生什么。 Consider how this will affect the error status of
cin
, what it will do if you try to read another integer from it when the last attempt yielded an error, and what inputValue
will be. 考虑一下这将如何影响
cin
的错误状态,如果在上次尝试产生错误时尝试从cin
中读取另一个整数,将如何inputValue
,以及inputValue
将是什么。
It may be the case that you still need a "SanityCheck"...but it may be able to take for granted that it only needs to check integers. 在某些情况下,您仍然需要“ SanityCheck” ...但是它可以理所当然地认为它只需要检查整数。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.