c++: how to input data on command line.

Hi.
I'm trying to input 2-dimensional array data from command line (i.e. not file data).
My question is how to do that? For one dimension array, I can separate data with "space", but how should I do for 2-dimensional data?

Thank you.
You can use end line '\n' for the rows (using function std::getline()) and spaces for columns (using >>) like so:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
#include <sstream>
#include <string>
#include <iostream>
#include <vector>

int main(int argc, char* argv[])
{
  std::string line;
  if(std::getline(std::cin, line))
  {
    if(! line.empty())
    {
      std::stringstream ss(line);
      std::vector<std::string> v;
      while(ss.good())
      {
        std::string s;
        ss >> s;
        v.push_back(s);
      }
    }
  }
}
Hi, coder777, thank you.
But, it's too difficult for me.
Even if the code is useful, how can I use this to get 2D_data into 2D_array, like k[i][j]?
If it's to diffult I'd suggest that you use a debugger and going thru it step by step and see what happens. Here it comes for k:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
#include <sstream>
#include <string>
#include <iostream>
#include <vector>

int main(int argc, char* argv[])
{
  std::vector<std::vector<std::string> > k;
  std::string line;
  if(std::getline(std::cin, line))
  {
    if(! line.empty())
    {
      std::stringstream ss(line);
      std::vector<std::string> v;
      while(ss.good())
      {
        std::string s;
        ss >> s;
        v.push_back(s);
      }
      k.push_back(v); // place the 'push_back()' here if you want no empty lines otherwise outside this 'if' (move it under the following '}')
    }
  }
}
Then you can use k[i][j]

Sorry that I can't make it simplier. This might give you the idea:

http://www.cplusplus.com/reference/stl/vector/
http://www.cplusplus.com/reference/iostream/stringstream/
http://www.cplusplus.com/reference/string/getline/
Topic archived. No new replies allowed.