0

我是在 C++ 中使用向量的新手,我的目标是从文本文件中读取一个矩阵并将它们存储到一个二维向量中,我的代码如下:

#include <fstream>
#include <iostream>
#include <sstream>
#include <string>
#include <vector>
int main()
{
    std::ifstream in("input.txt");
    std::vector<std::vector<int> > v;

    if (in) {
        std::string line;

        while (std::getline(in, line)) {
            v.push_back(std::vector<int>());

            // Break down the row into column values
            std::stringstream split(line);
            int value;

            while (split >> value)
                v.back().push_back(value);
        }
    }

    for (int i = 0; i < v.size(); i++) {
        for (int j = 0; j < v[i].size(); j++)
            std::cout << v[i][j] << ' ';

        std::cout << '\n';
    }
}

现在输入说

10101010
01010101
10101011
01011010

我得到一个输出

10101010
1010101
10101011
1011010

即,每次在行首遇到 0 时,都会将其省略。我相信问题出在语句 while(split>>value) 中,但我不知道如何以更好的方式对其进行编码。

4

2 回答 2

1

代替

while (split >> value)
    v.back().push_back(value);

for(int x=0; x<line.size(); x++){
    v.back().push_back((int)line[x] - (int)'0'));
}

并完全删除您的字符串流。

于 2017-10-16T20:22:53.427 回答
1

似乎您实际上想要存储位,但不知何故难以将包含例如10101010一系列位的行解析。如果您知道每行的最大位数,则可以使用bitset<N>,它为运算符提供了易于使用的重载>>,可以直接读取类似10101010. 希望能帮助到你。

int main()
{
    std::ifstream in("input.txt");
    std::vector<std::bitset<8> >v;

    if (in) {
        std::bitset<8> bits;
        while (in >> bits) {
            v.push_back(bits);
        }
    }

    for (int i = 0; i < v.size(); i++) {
        for (int j = 0; j < v[i].size(); j++)
            std::cout << v[i][j] << ' ';

        std::cout << '\n';
    }
}
于 2017-10-16T20:34:32.793 回答