0

As the title, how could I read different length of data into 2d array? And I know the upper limit of data length for each line. like..

5 6 9 8 4

5 4 9 5 6 5

1 2 3

4 5

I want to input these data into each row of 2d array, but c++'s cin will skip the input which is '\n'

so the method below doesn't work

for(int i=0; i<m; i++)
{
 int ch=0;
 while( (cin >> ch)!='\n' )
 {   
  element[i][ch] = true;
 }
}

so, how could I fix this? or, how could I distinguish '\n'? to let my "while" know that . thx a lot.

  • Urgently recommended read: [Are there any valid use cases to use new and delete, raw pointers or c-style arrays with modern C++?](https://stackoverflow.com/questions/46991224/are-there-any-valid-use-cases-to-use-new-and-delete-raw-pointers-or-c-style-arr) – user0042 Dec 28 '17 at 19:24
  • To catch up with line endings use `std::getline()`. – user0042 Dec 28 '17 at 19:26
  • Why don't you use `std::vector` so they don't have to be the same length? – Barmar Dec 28 '17 at 19:26
  • Why are you using the numbers as array indexes? – Barmar Dec 28 '17 at 19:28
  • Thx for your reply. The input in first line (5 6 9 8 4)means that point1 could approach point 5 6 9 8 4. Therefore, I wold like to choose element[0][5,6,9,8,4] = true. – brandonfang Jan 02 '18 at 09:19

1 Answers1

1

Use std::getline() to read a line into a string. Create a std::stringstream from that and then read each number into an array element.

std::string line;
int row = 0;
while(std::getline(cin, line)) {
    std::stringstream linein(line);
    int num;
    int col = 0;
    while (linein >> num) {
        element[row][col++] = num;
    }
    row++;
}
Barmar
  • 741,623
  • 53
  • 500
  • 612