2017-04-13 1 views
0

Salut J'aimerais exprimer cela en vecteur C++ < bitset < 8 >> s {s1, s2, ..., sn}; n est le numéro de l'élément dans le fichier. Donc, j'ai fait cnt pour compter les éléments dans le fichier. Donc, j'ai fait ce code. Mais je pense que mon code n'est pas correct. Mais je ne sais pas comment réparer ça.Comment puis-je exprimer ces éléments à C++

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

Voir [? Pourquoi iostream :: eof dans une condition de la boucle considérée comme erronée] (http://stackoverflow.com/questions/5605125/why-is -iostreameof-inside-a-loop-condition-considered-wrong) –

+0

Copie possible de [lire la chaîne à partir du fichier et la transformer en bitset <12>] (http://stackoverflow.com/questions/43381239/read-string-from-file -et-tour-en-bitset12) – chbchb55

+1

Votre dernière boucle for ne fait rien d'utile il semblerait. – chbchb55

Répondre

1

Votre code peut être beaucoup simplifié. Voici un exemple:

// 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. 
} 

Pour en savoir plus: Why is iostream::eof inside a loop condition considered wrong?

+2

Ant que 'for' boucle pourrait probablement être encore simplifié comme' pour const auto & file: fichiers) ':) –