首页 > 解决方案 > 如何在 C++ 中部分填充数组

问题描述

我正在尝试部分填充数组,但是在运行时,程序继续运行超过用户给出的限制。还有另一种方法来部分填充数组吗?

最初的 NUM_ROWS 和 NUM_COLUMNS 常量是占位符,直到程序工作

#include <iostream> // Input and output
#include <iomanip> // Input manipulator
#include <array>
using namespace std;

// Number used to initialize an array
const int NUM_ROWS = 10;
const int NUM_COLS = 10;

int userFilledArray[NUM_ROWS][NUM_COLS];

int row; // Amount of rows the user will fill
int col; // Amount of columns the user will fill

int main()
{
   
    int num; // Number that is placed in a specific row and column
    
    int total; // Total of every integer in the array
    int average; // Average of every integer in the array
    int rowTotal; // Total of every integer in a specific row
    int colTotal; // Total of every integer in a specific column
    int highestInRow;
    int lowestInRow;
    
    
    // Asks the user to enter the number of rows they would like to fill
    cout << "How many rows in the array would you like to fill? (Between 1 - 10)" << endl;
    cin >> row;
    
    // Asks the user to enter a number between 1-10 if the user enters a character or integers not between 1-10
    while (row < 0 || row > 10)
    {
        cout << "Please enter a number between 1-10" << endl;
        cin >> row;
    }
    
    // Asks the user to enter the number of columns they would like to fill
    cout << "How many columns in the array would you like to fill? (Between 1 - 10)" << endl;
    cin >> col;
    
    // Asks the user to enter a number between 1-10 if the user enters a character or integers not between 0-10
    while (col < 0 || col > 10)
    {
        cout << "Please enter a number between 1-10" << endl;
        cin >> col;
    }
    
    // Now the user will fill the array with as many numbers needed
    
    for (int i = 0; i < row; i++) // WARNING!!! NOT WORKING
    {
        for (int j = 0; i < col; j++) // WARNING!!! NOT WORKING
        {
            cout << "Enter a number for row " << i << " and column " << j << endl;
            cin >> num;
            userFilledArray[i][j] = num;
        }
    }
    
    total = getTotal(userFilledArray);
    cout << total << endl;
        
}

这是无法正常工作的区域

 // Now the user will fill the array with as many numbers needed
    
    for (int i = 0; i < row; i++) // WARNING!!! NOT WORKING
    {
        for (int j = 0; i < col; j++) // WARNING!!! NOT WORKING
        {
            cout << "Enter a number for row " << i << " and column " << j << endl;
            cin >> num;
            userFilledArray[i][j] = num;
        }
    }

}

标签: c++

解决方案


这是您有问题的行:

    for (int j = 0; i < col; j++) // WARNING!!! NOT WORKING

它还说明了为什么单字母变量名会导致错误。您从前一个 for 循环中剪切并粘贴了它,并且您没有更改 variable 的每个实例i


推荐阅读