Search code examples
c++vector

How to read from cin into a vector


I am trying to build a mine sweeper like program that reads in program from stdin. The input is in the form

4 4
..*.
*...
....
**..

I have defined vector<vector<char>> mine_field and have resized it to the dimensions of the field. I envisioned reading in the input a line at a time like this (of course this would only be the first line)

 cin >> mine_field[0];

However, this does not work. What would be the best way to do this?

Edit: I also thought about looping and storing the value in each index, but wouldn't this try to put the whole string in each index where there is room only for a char?


Solution

  • First of all, you need to resize your vector to the limits (rowSize, colSize).

    vector<vector<char> > mine_field (rowSize, vector<char> (colSize));
    

    Analogously, you can initialize all positions using this same declarations.

    vector<vector<char> > mine_field (rowSize, vector<char> (colSize, 'a'));
    

    All positions in the mine_field vector will be initialize with the char a.

    To read from cin, just read normally:

    for (int i = 0; i < rowSize; i++){
        for (int j = 0; j < colSize; j++){
            cin >> mine_field[i][j];
        }
    }`