从cin读取矩阵

时间:2016-12-08 11:26:40

标签: c++

我想尝试阅读该输入

2
2
9 97
8 56
3
1 18 6
16 42 100
25 16 17

我无法获得数字9,97,8,56并将它们存储在

的矢量中

这是我的尝试

using namespace std;

int main() {

    int test;

    cin >> test;

    while (test--)
    {
        int ss_i;
        cin >> ss_i;

        vector<int> A(ss_i*ss_i);



    }
    return 0;
}

1 个答案:

答案 0 :(得分:0)

您需要填写string,然后通过std::istringstream访问整数。 还要考虑push_back将这些整数存储到vector

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

int main(){

    int size{ 16 };

    std::vector<int> numbers;
    numbers.reserve(size); //reserve memory


    for (int i = 0; i < size;){
        std::string ss_i; //number(s) to push_back


        std::cout << "Type in " << size - i << " more integers: ";
        std::getline(std::cin, ss_i);

        std::istringstream stringstream(ss_i); //load into stream

        int n;
        while (stringstream >> n){
            i++;
            numbers.push_back(n); //add to the vector
        }
    }

    std::cout << "The vector contains:\n";
    for (auto i : numbers){
        std::cout << i << ' ';
    }
    return 0;
}

示例运行:

Type in 16 more integers: 2
Type in 15 more integers: 2
Type in 14 more integers: 9 97
Type in 12 more integers: 8 56
Type in 10 more integers: 3
Type in 9 more integers: 1
Type in 8 more integers: 18 6
Type in 6 more integers: 16 42
Type in 4 more integers: 100 25 16 17
The vector contains:
2 2 9 97 8 56 3 1 18 6 16 42 100 25 16 17