rose.b
rose.b

Reputation: 31

How can I express this elements to c++

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

Upvotes: 0

Views: 81

Answers (1)

R Sahu
R Sahu

Reputation: 206607

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?

Upvotes: 1

Related Questions