【发布时间】:2020-02-07 01:44:37
【问题描述】:
我的 C++ 代码 出现问题,涉及从用户接收输入并根据该输入填充数组。对于我的 function fillArray(),我需要一种方法来读取一行中的所有输入,并用这些输入填充一个数组,直到用户最后输入 -1,不是正整数,或超过 20 个元素的阈值。
例如,如果我输入
1 2 3 4 5 6 -1 在一行上,我希望 displayArray() 函数输出 1 2 3 4 5 6,或者如果我写 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21,我希望 displayArray() 输出 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20。
似乎每当我最后输入 -1 时, displayArray() 输出类似
1 2 3 4 5 6 94837 或任意大的数字。如果有人可以帮助我解决这个问题,我将不胜感激,这是我的代码:
#include <iostream>
using namespace std;
const int CAPACITY = 20;
void displayArray(int array[], int numElements)
{
for (int i = 0; i < numElements; i++)
cout << array[i] << " ";
cout << endl;
}
void fillArray(int array[], int& numElements)
{
int arrayPosition = 0;
int testArrayPosition = 0;
int testArray[CAPACITY];
bool continueReading = true;
cout << "Enter a list of up to 20 integers or -1 to end the list";
do
{
cin >> valueEntered;
if (valueEntered == -1)
{
continueReading = false;
} else if (valueEntered != -1) {
array[arrayPosition] = valueEntered;
arrayPosition++;
}
} while ((continueReading==true) || (arrayPosition >= CAPACITY));
numElements = (arrayPosition+1);
}
int main()
{
int array[CAPACITY];
int numArrayElements = 0;
fillArray(array, numArrayElements);
displayArray(array, numArrayElements);
cout << "NumArrayElements: " << numArrayElements << endl;
}
【问题讨论】:
-
请提供minimal reproducible example。您发布的代码无法编译。
-
您想在 do while 循环结束时将条件更改为
while ((continueReading && arrayPosition < CAPACITY),同时numElements应设置为arrayPosition,而不是arrayPosition + 1。