Roger_88
Roger_88

Reputation: 477

How to put numbers from a file in a vector of vectors?

I'm trying to read a file filled with numbers only, no spaces. I need to put these numbers four to four in a vector of vectors. Here what I tried and didn't work because is not showing anything.

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;
}

file.txt

0110010010100101100111110011111010011011001011100001111110001100101100

Expected output:

0110
0100
1010
0101
1001
1111

Upvotes: 0

Views: 88

Answers (1)

Jabberwocky
Jabberwocky

Reputation: 50831

Your logic is wrong and odd. This is a correct version:

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;
}

Upvotes: 3

Related Questions