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.

5
  • Urgently recommended read: Are there any valid use cases to use new and delete, raw pointers or c-style arrays with modern C++? Commented Dec 28, 2017 at 19:24
  • To catch up with line endings use std::getline(). Commented Dec 28, 2017 at 19:26
  • Why don't you use std::vector so they don't have to be the same length? Commented Dec 28, 2017 at 19:26
  • Why are you using the numbers as array indexes? Commented Dec 28, 2017 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. Commented Jan 2, 2018 at 9:19

1 Answer 1

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++;
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.