0

I'm trying to read a 2-dimensional array from the console but my code is wrong and reads twice my last line, what am I doing wrong??

Example INPUT:

1

01

10

OUTPUT:

10

10

    int n;
    cin>>n;
    char *A=new char[n,n];

    for(int i=0; i<n; i++)
    {
        for(int j=0; j<n; j++)
        {
            cin>>A[i,j];
        }
        cin.ignore();
    }
Victor
  • 21
  • 4

2 Answers2

0

Looking at your code I take it you are trying to make the 2D Array a dynamic size, however your syntax is wrong for declaring as well as populating the array. Think of a 2d Array as an array of pointers to an array. This question has been previously asked and answered:

How do I declare a 2d array in C++ using new?

Community
  • 1
  • 1
Ralph
  • 70
  • 2
  • 11
0

You've stumbled into the trap of the comma operator (not uncommon). It's valid C++ but it doesn't do what you want see: How does the Comma Operator work. You might want to do it like this:

cin>>n; 

std::vector<std::vector<std::string>> A; 

for(int i=0; i<n; i++) 
{ 
    A.push_back(std::vector<std::string>(n)); 

    for(int j=0; j<n; j++) { 
        if(!(cin >> A[i][j])) { 
            break; 
        } 
    } 

    if(!cin) 
        break; 
} 
Community
  • 1
  • 1
Oncaphillis
  • 1,888
  • 13
  • 15