1

I am a novice in C++. I am trying to get input from the user for inserting in a multidimensional vector. The code works fine. But when I give extra inputs in the same line, my program does not disregard it and considers it in the next iteration.

For example when I give input in the following format:

m=3 n=4

1 2 3 4 5
1 3 5 5
1 345 65 567

the output is

1   2   3   4
5   1   3   5
5   1 345  65

But what the output I want is

1   2   3   4
1   3   5   5
1   345 67  567
int main() {
    vector<vector<int>> vec;
    int m, n, dat;
    cout << "Enter dimensions of Vector";
    cin >> m >> n;
    // takes data n times into a subvector temp and inserts it into the vector vec m
    // times
    cout << "Enter elements one row at a time";
    for(int i = 0; i < m; ++i) {
        vector<int> temp;
        for(int j = 0; j < n; ++j) {
            cin >> dat;
            temp.push_back(dat);
        }
        vec.push_back(temp);
    }
    for(int k = 0; k < vec.size(); ++k) {
        for(int i = 0; i < vec[k].size(); ++i) {
            cout << setw(4) << vec[k][i];
        }
        cout << endl;
    }
}

1 Answers1

3

Consider using std::getline to read a complete line. You can then use that to populate a std::istringstream that you then use to extract the exact number of elements you want. Also note:

Why is “using namespace std;” considered bad practice?

Example:

#include <iomanip>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>

int main() {
    std::vector<std::vector<int>> vec;
    int m, n, dat;
    std::cout << "Enter dimensions of Vector";
    std::cin >> m >> n;
    std::cin.ignore(); // skip newline
    // takes data n times into a subvector temp and inserts it into the vector vec m
    // times
    std::cout << "Enter elements one row at a time\n";
    for(int i = 0; i < m; ++i) {
        std::string line;
        std::vector<int> temp;
        std::cout << " row " << (i + 1) << ": ";
        std::getline(std::cin, line);
        std::istringstream iss(line);
        for(int j = 0; j < n; ++j) {
            iss >> dat;
            temp.push_back(dat);
        }
        vec.push_back(temp);
    }
    for(const auto& row : vec) {
        for(int colval : row) {
            std::cout << std::setw(4) << colval;
        }
        std::cout << "\n";
    }
}
Ted Lyngmo
  • 93,841
  • 5
  • 60
  • 108