c++ - How to use cin with a variable number of inputs? -


i in programming competition yesterday , had read in input of form

n a1 a2 ... m b1 b2 ... bm ... 

where first line says how many inputs there are, , next line contains many inputs (and inputs integers).

i know if each line has same number of inputs (say 3), can write like

while (true) {     cin >> a1 >> a2 >> a3;     if (end of file)         break; } 

but how do when each line can have different number of inputs?

here's simple take using standard libraries:

#include <vector>       // vector #include <iostream>     // cout/cin, streamsize #include <sstream>      // istringstream #include <algorithm>    // copy, copy_n #include <iterator>     // istream_iterator<>, ostream_iterator<> #include <limits>       // numeric_limits  int main() {     std::vector<std::vector<double>> contents;      int number;     while (std::cin >> number)     {         std::cin.ignore(std::numeric_limits<std::streamsize>::max(), '\n'); // skip eol         std::string line;         std::getline(std::cin, line);         if (std::cin)         {             contents.emplace_back(number);             std::istringstream iss(line);             std::copy_n(std::istream_iterator<double>(iss), number, contents.back().begin());         }         else         {             return 255;         }     }      if (!std::cin.eof())         std::cout << "warning: end of file not reached\n";      (auto& row : contents)     {         std::copy(row.begin(), row.end(), std::ostream_iterator<double>(std::cout," "));         std::cout << "\n";     } } 

see live on coliru: input

5 1 2 3 4 5 7  6 7 8 9 10 11 12 

output:

1 2 3 4 5  6 7 8 9 10 11 12 

Comments

Popular posts from this blog

java - Run a .jar on Heroku -

java - Jtable duplicate Rows -

validation - How to pass paramaters like unix into windows batch file -