How to take input for a scenario like this: first line contains the number of test cases, and subsequent lines are array elements without size.
Example input:
2
1 5 6 7 8
8 9 5 4 3
How to take input for a scenario like this: first line contains the number of test cases, and subsequent lines are array elements without size.
Example input:
2
1 5 6 7 8
8 9 5 4 3
Here's an example, but it doesn't check for invalid input.
The key is to read each line using std::getline
, then get it into an std::istreamstream
. Then any method from this thread applies, if you replace std::cin
with the name of your stringstream (ss
in this example).
#include <iostream>
#include <iterator>
#include <limits>
#include <sstream>
#include <vector>
int main()
{
// Read the number of lines.
int n;
std::cin >> n;
// Skip the rest of the first line, including the line break.
std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n');
// Repeat `n` times.
while (n-- > 0)
{
// Read the next line.
std::string line;
std::getline(std::cin, line);
// Construct a string stream from the line.
// Now you can read from it as you would from `std::cin`.
std::istringstream ss(line);
// Get all numbers from the stream into an `std::vector`.
std::vector<int> vec(std::istream_iterator<int>(ss), {});
// Print the vector.
for (int x : vec)
std::cout << x << "; ";
std::cout << '\n';
}
}