Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <vector>
- #define NELEM 6 /* constant for correct number of elements */
- int main (void) {
- int i, last = 0; /* int read and last seen */
- std::vector<std::vector<int>> v {}; /* vector of vector<int> */
- std::vector<int> tmp {}; /* temporary vector<int> to fill */
- while (std::cin >> i) { /* read each integer in file */
- last = i; /* save last i to test on loop exit */
- if (i == -1) { /* if -1 array ended with last int */
- if (tmp.size() < NELEM) /* is size less than NELEM? */
- std::cerr << "\nthe array does not have enough integers.\n";
- else if (tmp.size() > NELEM) /* otherwise if greater than NELEM */
- std::cerr << "\nyou have too many numbers in this array.\n";
- else {
- v.push_back(tmp); /* add tmp to vector<vector<int>> */
- std::cout << "\nthe size of the array is correct.\n";
- }
- tmp.clear(); /* clear temporary vector<int> */
- continue;
- }
- std::cout << " " << i; /* output element */
- if (i < 0) { /* check if number is negative */
- std::cerr << "\nthis array has negative element.\n";
- while (std::cin >> i && (last = i) != -1) {}/* read/discard rest */
- tmp.clear(); /* clear temp array */
- continue;
- }
- tmp.push_back(i); /* add int to temporary vector */
- }
- if (last != -1) /* validate last read is -1 */
- std::cerr << "error: last input not -1.\n";
- std::cout << "\ncorrect arrays:\n"; /* output good arrays */
- for (auto r : v) { /* loop over good vectors */
- for (auto c : r) /* loop over integers */
- std::cout << " " << c; /* output values */
- std::cout << '\n'; /* tidy up with newline */
- }
- }
- /*
- echo "1 2 3 4 5 6 -1 1 2 3 4 -1 1 2 -3 4 5 6 7 8 -1 1 2 3 4 5 6 7 -1 2 3 4 5 6 7 -1" | ./bin/readmultiarray
- 1 2 3 4 5 6
- the size of the array is correct.
- 1 2 3 4
- the array does not have enough integers.
- 1 2 -3
- this array has negative element.
- 1 2 3 4 5 6 7
- you have too many numbers in this array.
- 2 3 4 5 6 7
- the size of the array is correct.
- correct arrays:
- 1 2 3 4 5 6
- 2 3 4 5 6 7
- */
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement