Getting user input into a 2D array

I need to figure out how to get a string of user input into a 2d array. The array is to be a square (equal number of rows and cols). The user is to input the size of the array. I know about using nested loops to get input into a 2D array.

Here's the catch though - The user is to input each row as a string of numbers with spaces, like so (if the user enters 5 for the size of the array):

1 2 3 4 5
(this would be the input for one row. this would be repeated for 5 rows)

Some how I have to break up that string and put the numbers into the proper row of the array.

Last edited on
Formatted input does not care whether you use space, tabs, newlines, (or all) between values.
See http://www.cplusplus.com/reference/istream/istream/operator%3E%3E/
Every example and tutorial I can find on putting user input into a 2D array has the user inputing one element at a time (and hitting return after each input). I looked at the reference above. But, no matter what I try I can't figure out how to accept a string of integers with spaces in between. Here's some code I wrote.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
#include <iostream> //for output to screen and input from screen
#include <string> //use of strings
#include <cstring> //use of c-style strings

using namespace std;

//function prototype
//int sameSum (int square[10][10], int rowNumber);

int main()
{
    int row;
    int col;
    int square[row][col];    //declare square

    cout<<"Enter row size: ";
    cin>>row;

    col = row;

    int i,j;
    cout<<"Enter Data in square"<<endl;
    for(i = 0; i < row; i++)
    {
        for(j = 0; j < col; j++)
        {
            cout<<"Enter row ["<<i<<"]: ";
            cin>>square[i][j];
        }
    }

    return 0;
}



Enter row size: 3
Enter Data in square
Enter row [0]: 1 2 3
Enter row [0]: Enter row [0]: Enter row [1]:
That does read the values properly. The problem is in the output that seems misplaced.
Add cout<<"\nGot ("<<i<<','<<j<<") "<<square[i][j]<<endl; after line 28 and you will get:
Enter row size: 2
Enter Data in square
Enter row [0]: 1 2 3 4

Got (0,0) 1
Enter row [0]:
Got (0,1) 2
Enter row [1]:
Got (1,0) 3
Enter row [1]:
Got (1,1) 4


You have a more serious error on line 14: size of static array must be known during compilation. The size of square is undefined.
Topic archived. No new replies allowed.