简体   繁体   中英

User input in 2D array (C++)

Not sure why the for loop won't save the correct values in the 2D array when I printed to check. Any ideas?

#include <iostream>
using namespace std;

int row, col; 

int main()
{
int num;
int val[row][col];

cout << "How many rows are there?" << endl;    
cin >> row;
cout << "How many columns are there?" << endl;
cin >> col;
cout << "Enter values for the matrix: " << endl;

for (int i = 0; i < row; i++)                 
{
    for (int j = 0; j < col; j++)
    {
        cin >> val[i][j]; 
    }   
}
return 0;
}
#include <iostream>
using namespace std;

int main()
{
    int row, col; 

    cout << "How many rows are there?" << endl;    
    cin >> row;
    cout << "How many columns are there?" << endl;
    cin >> col;
    cout << "Enter values for the matrix: " << endl;

    // check if row and col > 0
    int* val = new int[row * col];

    for (int i = 0; i < row; i++)                 
    {
        for (int j = 0; j < col; j++)
        {
            cin >> val[i * col + j]; 
        }   
    }
    delete[] val;
    return 0;
}

This doesn't do what you think it does. First of all, row and col are zero-initialized at program startup. Then you have int val[row][col]; which isn't valid C++ but rather a C variable length array. Since at this point row and col are both 0, this array will be of length zero.

In your loop you then read a bunch of values, overwriting what is on the stack and leading to undefined behavior.

You should instead use something that is dynamically allocated, like std::vector or a proper matrix class from the math library of your choosing. Using dynamic allocation manually ( new int[row * col] as suggested by Ali) is generally not recommended, since it's very easy to get memory leaks this way, especially if exceptions are involved.

If variable length arrays would be supported in C++ you could write what you wanted by just shifting:

int val[row][col];

To the point where row and col are known. Check this post: Why aren't variable-length arrays part of the C++ standard? Otherwise your code has undefined behavior. You should use dynamic allocation.

First, you can't have

int val[row][col];

before row and col have known values. Second, that kind of 2D array initialization is only standard in C.

You would need to manually allocate the array on the heap using the C++ operator new[] (similar to the malloc function in C). However that's not idiomatic C++ and the whole point of the language is to avoid doing that which is why I won't explain how to do it.

The proper C++ way to accomplish what you want is to use an std::vector, which a very powerful wrapper around C style arrays that automatically allocates and de-allocates memory for you (and a lot of other things).

Here's the simplest way to do that:

#include <iostream>
#include <vector>

using namespace std;

int main()
{
    int row;
    cout << "How many rows are there?" << endl;
    cin >> row;

    int col;
    cout << "How many columns are there?" << endl;
    cin >> col;

    int num;
    cout << "Enter values for the matrix: " << endl;
    cin >> num;

    vector<vector<int>> values(col); //initialize outer vector with col inner vectors

    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
        {
            values[i].push_back(num);
        }
    }

    for (int i = 0; i < row; i++)
    {
        for (int j = 0; j < col; j++)
        {
            cout << values[i][j];
        }

        cout << endl;
    }

    return 0;
}

Also, I advise you name your variables with more meaning and that you avoid using namespace std.

EDIT: From the way you approach the program, I assume in my answer you are familiar with C. If that's not the case, and you're following a book or tutorial, you should find a better book or tutorial.

#include <iostream>
#include <cstdlib>
#include <fstream>

using namespace std;

int main() {
int squareOrder;
const int MAX_SIZE = 5;
int squareArray[MAX_SIZE][MAX_SIZE] = {0};
int i;
int j;


cout << "What is the order of the square to be tested?";

cin >> squareOrder;

cout << endl << "Please enter the " << squareOrder*squareOrder << " values for the magic square in row major order: ";

for (i = 0; i < MAX_SIZE; i++) {
    for (j = 0; j < MAX_SIZE; j++) {
            cin >> squareArray[i][j];
    }
}


for (i = 0; i < MAX_SIZE;  i++) {
    for (j = 0; j < MAX_SIZE; j++) {
            cout << squareArray[i][j];
    }
}

return 0;
}

I have the following code, and when I go to run the program, the user input seems to be an infinite loop? The only way for the program to stop receiving user input is if there's an invalid input (anything besides an integer). I'm trying to see if the numbers are being stored the way I envision them to be before continuing on. Thanks for any help in advance!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM