0

Hi I'd like express this into c++ vector< bitset<8>> s{ s1, s2,..., sn }; n is the number of the element in the file. So, I made cnt to count the elements in the file. So, I made this code. But I think my code is not right. But I don't know how to fix this.

int cnt;
for (int x = 0; x < sizeof(files) / sizeof(files[0]); x++) {
    std::ifstream f;

    f.open(files[x].c_str(), std::ios::in);
    if (f.good()) {
        while (!f.eof()) {//end of file check
            f >> str;
            bitset<8> s(str);
            cnt++;
            str.clear();
        }
        f.close();
    }

    for (int i = 0; i < cnt; i++){ 
        vector<bitset<8>> s{ s[i] };
    }
}
rose.b
  • 21
  • 1
  • 2
    See [Why is iostream::eof inside a loop condition considered wrong?](http://stackoverflow.com/questions/5605125/why-is-iostreameof-inside-a-loop-condition-considered-wrong) – R Sahu Apr 13 '17 at 05:05
  • Possible duplicate of [read string from file and turn into bitset<12>](http://stackoverflow.com/questions/43381239/read-string-from-file-and-turn-into-bitset12) – Chris Apr 13 '17 at 05:08
  • 1
    Your last for loop doesn't do anything useful it would seem. – Chris Apr 13 '17 at 05:12

1 Answers1

1

Your code can be simplified a lot. Here's a sample:

// Create the vector of bitsets. It is empty to start with.
vector<bitset<8>> s;

// Go through each file.
for (int x = 0; x < sizeof(files) / sizeof(files[0]); x++)
{
   // Open the file.
   // std::ifstream f(files[x].c_str()); // For pre C++11.
   std::ifstream f(files[x]);            // For C++11 or later.

   // Define str here.
   // It should not be needed outside the for loop.
   std::string str;

   // Keep reading from the file until read fails.
   while (f >> str)
   {
      // Construct a bitset from the string.
      bitset<8> si(str);

      // Add the bitset to the vector of bitsets.
      s.push_back(si);
   }

   // There is no need to explicitly close the file.
   // The destructor will take care of that.
}

Further reading: Why is iostream::eof inside a loop condition considered wrong?

Community
  • 1
  • 1
R Sahu
  • 196,807
  • 13
  • 136
  • 247