【问题标题】:How to put numbers from a file in a vector of vectors?如何将文件中的数字放入向量向量中?
【发布时间】:2018-03-20 15:19:01
【问题描述】:

我正在尝试读取一个仅包含数字且没有空格的文件。我需要将这些数字四到四放入向量向量中。在这里我尝试过但没有工作,因为没有显示任何内容。

vector<vector<int>> vectorReader(string path) {
    ifstream file( path );
    int i;
    char bit;
    vector<vector<int>> fle;
    vector<int> word;

    i = 0;

    if(file.is_open()){
        while(file >> bit){
            if(i % 4 == 0) {
                fle.push_back(word);
                vector<int> word;
            }
            else {
                word.push_back((bit - 48));
                i++;
            }
        }
    }
    else{
        cout << "Error!.\n\n";
    }

    fle.erase( fle.begin() );

return fle;
}


int main(){
    string path = "file.txt";

    vector<vector<int>> file = vectorReader( path );
    for(const auto &line : file) {
        for(const auto &val : line) {
            cout << val;
        }
        cout << endl;
    }

    return 0;
}

文件.txt

0110010010100101100111110011111010011011001011100001111110001100101100

预期输出:

0110
0100
1010
0101
1001
1111

【问题讨论】:

  • 通过“不显示任何内容”,值没有出现在向量中?你能澄清一下你的意思吗?
  • 请显示触发问题的file.txt 文件的最小示例,并显示预期的输出应该是什么。
  • 顺便说一句,这行中48 的幻数是什么:word.push_back((bit - 48));
  • 我现在正在研究这个问题。似乎有一些编译问题开始......
  • @Roger_88 是的,感谢您对文件的描述。这改变了很多问题所在。

标签: c++ file vector


【解决方案1】:

你的逻辑是错误的和奇怪的。这是一个正确的版本:

vector<vector<int>> vectorReader(string path) {
  ifstream file(path);
  char bit;
  vector<vector<int>> vec;
  vector<int> word;

  int i = 0;

  if (file.is_open()) {
    while (file >> bit) {
      word.push_back((bit - '0'));    // add digit in word vector

      if (++i % 4 == 0) {             // if 4 digits have been added to word vector
        vec.push_back(word);          //   add word to vec vector
        word.clear();                 //   and clear word vector for next iteration
      }
    }
  }
  else {
    cout << "Error!.\n\n";
  }

  return vec;
}

【讨论】:

  • 您的代码未显示前 4 个数字。第一个字。
  • 对不起,你是对的。现在工作正常。非常感谢!
猜你喜欢
  • 2019-11-16
  • 1970-01-01
  • 1970-01-01
  • 2014-05-14
  • 2017-08-10
  • 2019-03-11
  • 2011-04-01
  • 1970-01-01
  • 2012-12-28
相关资源
最近更新 更多